#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Processing folders: pipelines on any folder, processed in place (#7874)
Reece Brownee1f94f711d0f
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex a6160de0a3..cfdf3c8c7b 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -211,10 +211,20 @@ public class ApplicationProperties {* write to. Empty (the default) disables folder access except to implicitly defined* folders, such as server storage folders (if enabled) and the pipeline watched folders.* Stirling's own config directory is always off-limits, and folder access is always- * disabled in SaaS mode regardless of this list.+ * disabled in SaaS mode regardless of this list. Processing folders let every authenticated+ * user, not only team leaders, read and replace files under these roots.*/private List<String> allowedFolderRoots = new java.util.ArrayList<>();+ /**+ * How many of one sweep's runs may execute at once; further runs queue, visible as pending.+ * A folder dispatched all at once piles up at the pipeline's slowest tool and nothing+ * visibly finishes until the end, so the cap keeps completions arriving steadily. The+ * default suits API-bound pipelines; turn it down for a heavyweight local engine, 0 =+ * unbounded.+ */+ private int sweepConcurrency = 6;+/** How often (seconds) the schedule trigger checks for policies whose schedule is due. */private long scheduleSweepSeconds = 60;diff --git a/app/common/src/main/java/stirling/software/common/service/UserServiceInterface.java b/app/common/src/main/java/stirling/software/common/service/UserServiceInterface.javaindex 9649696567..34ef739b8b 100644--- a/app/common/src/main/java/stirling/software/common/service/UserServiceInterface.java+++ b/app/common/src/main/java/stirling/software/common/service/UserServiceInterface.java@@ -9,6 +9,13 @@ public interface UserServiceInterface {long getTotalUsersCount();+ /**+ * Whether a user is stored under exactly this name. Exact, not case-insensitive: callers use it+ * to decide whether a record stamped with an owner name is still reachable, and reachability is+ * decided by an exact name match.+ */+ boolean usernameExists(String username);+boolean isCurrentUserAdmin();boolean isCurrentUserFirstLogin();diff --git a/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.java b/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.javaindex ca8c22624c..b26b9b06d8 100644--- a/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.java+++ b/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.java@@ -67,11 +67,17 @@ public class FileReadinessChecker {return false;}- if (!hasSettled(path, config.getSettleTimeMillis())) {+ Long ageMillis = fileAgeMillis(path);+ if (ageMillis == null || ageMillis < config.getSettleTimeMillis()) {return false;}- if (!hasSizeStabilized(path, config.getSizeCheckDelayMillis())) {+ // The size-stability wait exists to catch an active copy whose writer pauses+ // between chunks. A file untouched for twice the settle window has provably+ // stopped changing, and the wait sleeps per file - paying it for old files+ // turns a backlog scan over a folder-sized directory into minutes of dead time.+ if (ageMillis < config.getSettleTimeMillis() * 2+ && !hasSizeStabilized(path, config.getSizeCheckDelayMillis())) {return false;}@@ -123,30 +129,16 @@ public class FileReadinessChecker {return allowed;}- /**- * Returns {@code true} when the file's last-modified timestamp is at least {@code- * settleTimeMillis} milliseconds in the past, indicating the write has completed and the file- * has "settled".- */- private boolean hasSettled(Path path, long settleTimeMillis) {+ /** Milliseconds since the file was last modified; null when the timestamp cannot be read. */+ private Long fileAgeMillis(Path path) {try {- long lastModified = Files.getLastModifiedTime(path).toMillis();- long ageMillis = System.currentTimeMillis() - lastModified;- boolean settled = ageMillis >= settleTimeMillis;- if (!settled) {- log.debug(- "File '{}' was modified {}ms ago (settle threshold: {}ms), not yet ready",- path.getFileName(),- ageMillis,- settleTimeMillis);- }- return settled;+ return System.currentTimeMillis() - Files.getLastModifiedTime(path).toMillis();} catch (IOException e) {log.warn("Could not read last-modified time for '{}', treating as not settled: {}",path,e.getMessage());- return false;+ return null;}}diff --git a/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.java b/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.javaindex ebede973ea..5a93d106ee 100644--- a/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.java+++ b/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.java@@ -207,6 +207,21 @@ class FileReadinessCheckerTest {@DisplayName("size-stability check")class SizeStability {+ @Test+ @DisplayName("a long-settled file skips the size-stability wait")+ void oldFileSkipsStabilityWait() throws IOException {+ config.setSettleTimeMillis(1_000);+ config.setSizeCheckDelayMillis(5_000); // would dominate a backlog scan+ Path file = realFile("old.pdf", "content");+ setLastModifiedInPast(file, 60_000);++ long start = System.currentTimeMillis();+ assertTrue(checker.isReady(file));+ assertTrue(+ System.currentTimeMillis() - start < 2_000,+ "the per-file stability wait was paid for a long-settled file");+ }+@Test@DisplayName("size unchanged between two reads → ready")void sizeStable_ready() throws IOException {@@ -220,8 +235,11 @@ class FileReadinessCheckerTest {@DisplayName("size changes between two reads → not ready")void sizeChanging_notReady() throws IOException {config.setSizeCheckDelayMillis(1);+ // Inside the copy window (settled, but recently enough that a paused+ // mid-copy is plausible), so the stability check actually runs.+ config.setSettleTimeMillis(1_000);Path file = realFile("growing.pdf", "initial");- setLastModifiedInPast(file, 60_000);+ setLastModifiedInPast(file, 1_500);// Use MockedStatic to control what Files.size() returns on each call// while leaving all other Files.* methods intact.diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 0c01c91991..4fb4716764 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -409,7 +409,10 @@ aiEngine:policies:# Folder automations can read from and write to the directories you allow here, so treat this as a- # security boundary. Leave allowedFolderRoots empty (default) to disable folder sources/outputs,+ # security boundary. On a multi-user server EVERY authenticated user (not only team leaders) can+ # attach folder processing to directories under these roots - listing their contents and replacing+ # files in place - so only list directories all users may touch.+ # Leave allowedFolderRoots empty (default) to disable folder sources/outputs,# other than from directories that are always permitted like server file-storage and watched folders.# List absolute directories to permit folder access within them.# Stirling's own config directory is always off-limits, and folder access is alwaysdiff --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.javaindex 92ab91e99c..a1caa1a6ad 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,6 +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>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;@@ -46,6 +49,7 @@ public class FolderAccessGuard {public record ImpliedRoot(Path path, String reason) {}private final boolean saasActive;+ private final boolean desktopOperator;private final List<Path> allowedRoots;private final List<ImpliedRoot> impliedRoots;private final List<Path> protectedRoots;@@ -57,6 +61,8 @@ public class FolderAccessGuard {Environment environment,SourceStore sourceStore) {this.saasActive = Arrays.asList(environment.getActiveProfiles()).contains("saas");+ this.desktopOperator =+ isDesktopBundle() && !applicationProperties.getSecurity().isEnableLogin();this.allowedRoots =normalizeAll(applicationProperties.getPolicies().getAllowedFolderRoots());this.impliedRoots = impliedRoots(applicationProperties.getStorage(), runtimePathConfig);@@ -64,6 +70,19 @@ public class FolderAccessGuard {this.sourceStore = sourceStore;}+ /**+ * True only in the bundled desktop app, whose sidecar launches the jar with {@code+ * -DSTIRLING_PDF_TAURI_MODE=true}. Read from the JVM's own system properties so a server cannot+ * inherit it from the environment or settings.yml, and absent means "not desktop", which is the+ * safe side: a self-hosted server with login off is exactly the case this must not open up.+ *+ * <p>Unlike {@code HardwareKeyStoreService.isDesktop()} a {@code Client-*} machine type is not+ * accepted, because that only reflects {@code BROWSER_OPEN}, which any server can set.+ */+ private static boolean isDesktopBundle() {+ return Boolean.parseBoolean(System.getProperty("STIRLING_PDF_TAURI_MODE", "false"));+ }+/** Returns the normalised absolute path; throws if not permitted. */public Path requirePermitted(Path dir) {if (saasActive) {@@ -77,6 +96,11 @@ public class FolderAccessGuard {"folder may not point inside a protected Stirling directory");}}+ // The desktop operator's own choice is the authorization on their own machine; only the+ // SaaS refusal and the protected config dir above outrank it.+ if (desktopOperator) {+ return normalized;+ }// Stirling-owned implied roots are always permitted, even with no configured roots, so// automations work against them out of the box.if (impliedRoots.stream().anyMatch(root -> normalized.startsWith(root.path()))) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.javaindex 2d7061c966..067dc4f0b7 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.java@@ -40,20 +40,74 @@ public class PolicyAccessGuard {return enforced() ? policyManagementAuthority.currentUserTeamId() : null;}- /** Whether the policy belongs to the current user's team (so they may view/run/edit it). */+ /**+ * Whether the caller may view/run/edit this record: team membership for a policy. A+ * processing-folder pair is personal, not team governance, so only its owner reaches it {@code+ * -} teammates and team leaders alike do not.+ */public boolean canAccess(Policy policy) {if (!enforced()) {return true;}+ if (Policy.SURFACE_PROCESSING_FOLDER.equals(policy.surface())) {+ return ownedByCurrentUser(policy);+ }return Objects.equals(policy.teamId(), policyManagementAuthority.currentUserTeamId());}+ /**+ * Owner match for a personal record, fail-closed: a row with no stamped owner belongs to nobody+ * under login. Treating a null owner as anyone's would expose a legacy or mis-stamped folder to+ * every authenticated user, since this surface is owner-scoped, not team-scoped. The rows this+ * rejects are {@link #isOrphaned orphaned}, and the engine must refuse to run them.+ */+ private boolean ownedByCurrentUser(Policy policy) {+ return policy.owner() != null+ && Objects.equals(policy.owner(), userService.getCurrentUsername());+ }++ /**+ * Whether owner scoping leaves this processing folder reachable by nobody, so the engine can+ * refuse to run it rather than replace files in place in a folder no one can list, pause,+ * revert or delete.+ *+ * <p>Two ways in: a folder created while login was disabled is stamped with no owner, and+ * enabling login later strands it; a folder whose owner was renamed or deleted is stamped with+ * a name that no longer resolves. Existence is read by exact name, the same way {@link+ * #ownedByCurrentUser} matches, so a different case in the users table does not rescue it.+ */+ public boolean isOrphaned(Policy policy) {+ if (!enforced() || !Policy.SURFACE_PROCESSING_FOLDER.equals(policy.surface())) {+ return false;+ }+ return policy.owner() == null || !userService.usernameExists(policy.owner());+ }+/*** The policies visible to the caller: their whole team's, loaded scoped rather than fetched* globally and filtered, so on SaaS it never pulls another team's policies into memory. Login* disabled (single-user) returns everything.*/public List<Policy> visibleFrom(PolicyStore store) {+ // Processing-folder pairs share the store but belong to their own surface; nothing+ // that lists policies may see them, so the exclusion lives here, not at each caller.+ return scopedRows(store).stream()+ .filter(policy -> Policy.SURFACE_POLICY.equals(policy.surface()))+ .toList();+ }++ /**+ * The processing folders visible to the caller: of the team's rows, only the ones the caller+ * owns, since these are personal records. Login disabled returns them all.+ */+ public List<Policy> visibleProcessingFolders(PolicyStore store) {+ return scopedRows(store).stream()+ .filter(policy -> Policy.SURFACE_PROCESSING_FOLDER.equals(policy.surface()))+ .filter(policy -> !enforced() || ownedByCurrentUser(policy))+ .toList();+ }++ private List<Policy> scopedRows(PolicyStore store) {if (!enforced()) {return store.all();}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.javaindex 69a547c28b..9d3cdb3506 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java@@ -59,6 +59,7 @@ import stirling.software.proprietary.policy.engine.PolicyRunHandle;import stirling.software.proprietary.policy.engine.PolicyRunRegistry;import stirling.software.proprietary.policy.engine.PolicyRunner;import stirling.software.proprietary.policy.engine.PolicyValidator;+import stirling.software.proprietary.policy.engine.SweepKind;import stirling.software.proprietary.policy.engine.SweepOutcome;import stirling.software.proprietary.policy.ledger.ProcessedLedger;import stirling.software.proprietary.policy.model.OutputSpec;@@ -209,15 +210,20 @@ public class PolicyController {summary = "List the caller's stored-policy runs",description ="Returns the caller's in-flight and recently-finished stored-policy runs (within"- + " the run-retention window). The frontend reconciles these on load so a"- + " run started before a refresh/crash is rediscovered and its outputs"+ + " the run-retention window), optionally narrowed to one policy via"+ + " `policyId` — a client following a single sweep polls this every"+ + " second, and the unfiltered list grows with every other policy's"+ + " runs. The frontend reconciles the unfiltered list on load so a run"+ + " started before a refresh/crash is rediscovered and its outputs"+ " collected, rather than orphaned on the backend. Ad-hoc runs (no"+ " policy id) are excluded.")- public List<PolicyRunView> listRuns() {+ public List<PolicyRunView> listRuns(+ @RequestParam(name = "policyId", required = false) String policyId) {// Local runs first (they carry live step state); keyed by runId to dedupe shared entries.Map<String, PolicyRunView> byRunId = new LinkedHashMap<>();runRegistry.all().stream().filter(run -> run.getPolicyId() != null)+ .filter(run -> policyId == null || policyId.equals(run.getPolicyId())).filter(run -> ownedByCurrentUser(run.getRunId())).forEach(run -> byRunId.put(run.getRunId(), PolicyRunView.of(run)));// Then runs from other nodes, read from the shared job store.@@ -229,6 +235,9 @@ public class PolicyController {if (meta == null || !meta.containsKey("policyId")) {continue; // ad-hoc job, not a stored-policy run}+ if (policyId != null && !policyId.equals(meta.get("policyId"))) {+ continue;+ }if (ownedByCurrentUser(entry.jobId())) {byRunId.put(entry.jobId(), PolicyRunView.ofEntry(entry));}@@ -370,30 +379,44 @@ public class PolicyController {}}+ /**+ * The policies surface serves only its own records: a processing-folder pair reads as not-found+ * here even for a caller who could reach it through its own route, so this API can never see,+ * rewrite, or half-tear-down a pair.+ */+ private boolean accessiblePolicySurface(Policy policy) {+ return Policy.SURFACE_POLICY.equals(policy.surface())+ && policyAccessGuard.canAccess(policy);+ }+/*** Assign owner + owning team server-side. Create stamps the current user and their team; update* preserves the existing owner and team after verifying the policy belongs to the caller's team* — so the client can neither forge ownership/team on create nor reach across teams on update- * (a policy in another team reads as not-found).+ * (a policy in another team reads as not-found). The surface is stamped the same way: this+ * route writes only policy-surface rows.*/private Policy resolveOwnership(Policy incoming) {String id = incoming.id();if (id != null && !id.isBlank()) {Policy existing = policyStore.get(id).orElse(null);if (existing != null) {- if (!policyAccessGuard.canAccess(existing)) {+ if (!accessiblePolicySurface(existing)) {throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No policy: " + id);}- return withOwnerAndTeam(incoming, existing.owner(), existing.teamId());+ return withOwnerAndTeam(+ incoming, existing.owner(), existing.teamId(), existing.surface());}}return withOwnerAndTeam(incoming,policyAccessGuard.ownerForNewPolicy(),- policyAccessGuard.teamForNewPolicy());+ policyAccessGuard.teamForNewPolicy(),+ Policy.SURFACE_POLICY);}- private static Policy withOwnerAndTeam(Policy policy, String owner, Long teamId) {+ private static Policy withOwnerAndTeam(+ Policy policy, String owner, Long teamId, String surface) {return new Policy(policy.id(),policy.name(),@@ -406,7 +429,8 @@ public class PolicyController {policy.output(),policy.outputIds(),teamId,- policy.editor());+ policy.editor(),+ surface);}/** Output secrets never leave the server: reads return the redaction sentinel instead. */@@ -544,7 +568,7 @@ public class PolicyController {public ResponseEntity<Policy> getPolicy(@PathVariable String policyId) {return policyStore.get(policyId)- .filter(policyAccessGuard::canAccess)+ .filter(this::accessiblePolicySurface).map(PolicyController::withMaskedOutputSecrets).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());@@ -555,7 +579,8 @@ public class PolicyController {public ResponseEntity<Void> deletePolicy(@PathVariable String policyId) {requirePolicyEditingAllowed();// Scope to the caller's team: a policy in another team reads as not-found.- Policy policy = policyStore.get(policyId).filter(policyAccessGuard::canAccess).orElse(null);+ Policy policy =+ policyStore.get(policyId).filter(this::accessiblePolicySurface).orElse(null);if (policy == null) {return ResponseEntity.notFound().build();}@@ -580,8 +605,9 @@ public class PolicyController {public ResponseEntity<Void> clearProcessedHistory(@PathVariable String policyId) {requirePolicyEditingAllowed();// Scope to the caller's team: a policy in another team reads as not-found.- Policy policy = policyStore.get(policyId).filter(policyAccessGuard::canAccess).orElse(null);- if (policy == null) {+ boolean accessible =+ policyStore.get(policyId).filter(this::accessiblePolicySurface).isPresent();+ if (!accessible) {return ResponseEntity.notFound().build();}processedLedger.clearPolicy(policyId);@@ -605,7 +631,7 @@ public class PolicyController {Policy policy =policyStore.get(policyId)- .filter(policyAccessGuard::canAccess)+ .filter(this::accessiblePolicySurface).orElseThrow(() ->new ResponseStatusException(@@ -638,12 +664,12 @@ public class PolicyController {Policy policy =policyStore.get(policyId)- .filter(policyAccessGuard::canAccess)+ .filter(this::accessiblePolicySurface).orElseThrow(() ->new ResponseStatusException(HttpStatus.NOT_FOUND, "No policy: " + policyId));- return ResponseEntity.accepted().body(policyRunner.run(policy));+ return ResponseEntity.accepted().body(policyRunner.run(policy, SweepKind.USER));}private static void requireRunnable(PipelineDefinition definition) {@@ -726,7 +752,7 @@ public class PolicyController {}return policyStore.get(policyId)- .filter(policyAccessGuard::canAccess)+ .filter(this::accessiblePolicySurface).map(policy -> assetResolver.resolve(policy, inputs)).orElse(inputs);}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.javanew file mode 100644index 0000000000..1e5c56a181--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java@@ -0,0 +1,895 @@+package stirling.software.proprietary.policy.controller;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.StandardCopyOption;+import java.time.Duration;+import java.time.LocalDateTime;+import java.time.ZoneId;+import java.util.HashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Objects;+import java.util.UUID;+import java.util.stream.Stream;++import org.slf4j.MDC;+import org.springframework.http.HttpStatus;+import org.springframework.http.MediaType;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.DeleteMapping;+import org.springframework.web.bind.annotation.GetMapping;+import org.springframework.web.bind.annotation.PathVariable;+import org.springframework.web.bind.annotation.PostMapping;+import org.springframework.web.bind.annotation.RequestBody;+import org.springframework.web.bind.annotation.RequestMapping;+import org.springframework.web.bind.annotation.RestController;+import org.springframework.web.server.ResponseStatusException;++import io.swagger.v3.oas.annotations.Operation;+import io.swagger.v3.oas.annotations.tags.Tag;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.config.FolderAccessGuard;+import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.engine.PolicyEngine;+import stirling.software.proprietary.policy.engine.PolicyRunner;+import stirling.software.proprietary.policy.engine.PolicyValidator;+import stirling.software.proprietary.policy.engine.SweepKind;+import stirling.software.proprietary.policy.engine.SweepOutcome;+import stirling.software.proprietary.policy.ledger.ClaimState;+import stirling.software.proprietary.policy.ledger.FolderIdentities;+import stirling.software.proprietary.policy.ledger.ProcessedFileStatus;+import stirling.software.proprietary.policy.ledger.ProcessedLedger;+import stirling.software.proprietary.policy.ledger.StorageFileIdentities;+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.TriggerConfig;+import stirling.software.proprietary.policy.output.FolderOutputSink;+import stirling.software.proprietary.policy.source.Source;+import stirling.software.proprietary.policy.source.SourceStore;+import stirling.software.proprietary.policy.store.PolicyStore;+import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.model.FilePurpose;+import stirling.software.proprietary.storage.model.Folder;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.repository.FolderRepository;+import stirling.software.proprietary.storage.repository.StoredFileRepository;+import stirling.software.proprietary.storage.service.FileStorageService;++/**+ * Processing folders: a folder with a pipeline attached, so files that land in it are processed.+ * Each is a source + policy pair composed and torn down together here, marked with {@link #SURFACE}+ * and served only by this route. Personal, per-user records — no team-leader gate — still+ * team-stamped so engine scoping holds.+ */+@Slf4j+@RestController+@RequestMapping("/api/v1/processing-folders")+@RequiredArgsConstructor+@Tag(name = "Processing Folders", description = "Folders that process any file added to them.")+public class ProcessingFolderController {++ /** Legacy marker in output options; pre-surface-field rows carry it, and reads strip it. */+ public static final String SURFACE_OPTION = "surface";++ public static final String SURFACE = Policy.SURFACE_PROCESSING_FOLDER;++ /** The paired source's type; the policies/pipelines surfaces hide sources of this type too. */+ public static final String SOURCE_TYPE = "storage-folder";++ static final String DISK_SOURCE_TYPE = FolderAccessGuard.FOLDER_TYPE;++ /** The only extensions the disk pipeline claims; everything else is out of scope. */+ private static final List<String> DISK_EXTENSIONS = List.of(".pdf");++ /** Cap on files one sweep of a disk-backed folder takes; the rest wait for the next. */+ static final int DISK_SWEEP_LIMIT = 100;++ static final String WATCH_TRIGGER = "folder-watch";++ private final PolicyStore policyStore;+ private final SourceStore sourceStore;+ private final PolicyValidator policyValidator;+ private final PolicyRunner policyRunner;+ private final PolicyTriggerManager policyTriggerManager;+ private final ProcessedLedger processedLedger;+ private final FolderRepository folderRepository;+ private final StoredFileRepository storedFileRepository;+ private final FileStorageService fileStorageService;+ private final PolicyAccessGuard policyAccessGuard;+ private final FolderAccessGuard folderAccessGuard;+ private final ApplicationProperties applicationProperties;++ public record ProcessingFolderView(+ String id,+ String folderId,+ String directory,+ String name,+ boolean enabled,+ List<PipelineStep> steps,+ Map<String, Object> output) {}++ /**+ * Create/update payload: null id creates, present id updates. Exactly one of {@code folderId}+ * (app storage) or {@code directory} (server-disk path) says where the folder watches.+ */+ public record SaveProcessingFolderRequest(+ String id,+ String folderId,+ String directory,+ Boolean enabled,+ List<PipelineStep> steps,+ Map<String, Object> output) {}++ /** The server's Downloads directory and PDF count; the browser cannot see machine paths. */+ public record DownloadsSuggestion(+ String directory, boolean available, int pdfCount, int limit) {}++ @GetMapping("/downloads-suggestion")+ @Operation(+ summary = "The server's Downloads directory and how many PDFs are waiting in it",+ description =+ "Backs the offer to process a user's Downloads. `available` is false when the"+ + " directory does not exist or is outside the permitted folder roots,"+ + " so the offer is never made where it could only fail.")+ public DownloadsSuggestion downloadsSuggestion() {+ currentUserOrNull();+ Path downloads = Path.of(System.getProperty("user.home", ""), "Downloads");+ // Only return the path when the offer is available: it is the server's home directory+ // (hence the OS username) and must not leak to a caller who cannot use the folder.+ if (!Files.isDirectory(downloads)) {+ return new DownloadsSuggestion("", false, 0, DISK_SWEEP_LIMIT);+ }+ try {+ folderAccessGuard.requirePermitted(downloads);+ } catch (RuntimeException notPermitted) {+ return new DownloadsSuggestion("", false, 0, DISK_SWEEP_LIMIT);+ }+ int pdfCount = 0;+ try (Stream<Path> entries = Files.list(downloads)) {+ pdfCount =+ (int)+ entries.filter(Files::isRegularFile)+ .filter(+ path ->+ path.getFileName()+ .toString()+ .toLowerCase(Locale.ROOT)+ .endsWith(".pdf"))+ .limit(DISK_SWEEP_LIMIT * 10L)+ .count();+ } catch (IOException e) {+ log.debug("Could not count PDFs in {}: {}", downloads, e.getMessage());+ }+ return new DownloadsSuggestion(downloads.toString(), true, pdfCount, DISK_SWEEP_LIMIT);+ }++ @GetMapping+ @Operation(summary = "List the caller's processing folders")+ public List<ProcessingFolderView> list() {+ currentUserOrNull();+ return policyAccessGuard.visibleProcessingFolders(policyStore).stream()+ .map(this::toView)+ .toList();+ }++ @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)+ @Operation(+ summary = "Create or update a processing folder",+ description =+ "Composes the folder's source + pipeline pair, validated like any policy save."+ + " Creating one immediately processes the folder's existing files (the"+ + " ledger keeps already-processed files from re-running).")+ public ResponseEntity<ProcessingFolderView> save(+ @RequestBody SaveProcessingFolderRequest request) {+ User user = currentUserOrNull();+ boolean onDisk = request.directory() != null && !request.directory().isBlank();+ if (onDisk == (request.folderId() != null && !request.folderId().isBlank())) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST,+ "a processing folder needs either a folderId or a directory, not both");+ }+ Folder folder = onDisk ? null : requireOwnedFolder(request.folderId(), user);+ boolean requestedCreate = request.id() == null || request.id().isBlank();+ Policy existing =+ requestedCreate ? existingForPlace(request, user) : requireOwn(request.id(), user);+ if (requestedCreate && existing != null) {+ // A create over an existing folder adopts it as-is and sweeps the backlog;+ // reconfiguring is an update by id, so an offer flow overwrites nothing.+ sweepBehindTheResponse(existing);+ return ResponseEntity.accepted().body(toView(existing));+ }+ String name = onDisk ? diskFolderName(request.directory()) : folder.getName();++ // Held for rollback: the source is written before the policy validates, and a rejected+ // save must not leave the pair half-updated (source mutated, policy old).+ String existingSourceId = existing == null ? null : soleSourceId(existing);+ Source priorSource =+ existingSourceId == null ? null : sourceStore.get(existingSourceId).orElse(null);++ Source source =+ sourceStore.save(+ new Source(+ existing == null ? null : soleSourceId(existing),+ name,+ onDisk ? DISK_SOURCE_TYPE : SOURCE_TYPE,+ onDisk+ ? diskSourceOptions(request.directory())+ : Map.of("folderId", folder.getId().toString()),+ // Always enabled: pause lives on the policy, and sweeps+ // skip disabled sources, so a paused folder can still+ // sweep on demand.+ true,+ policyAccessGuard.ownerForNewPolicy(),+ policyAccessGuard.teamForNewPolicy()));+ Policy policy =+ new Policy(+ existing == null ? null : existing.id(),+ "Processing folder: " + name,+ policyAccessGuard.ownerForNewPolicy(),+ request.enabled() == null || request.enabled(),+ // Disk directories watch, so arrivals process on their+ // own; storage-backed folders stay manual for now.+ List.of(+ new PipelineInput(+ source.id(),+ onDisk+ ? new TriggerConfig(WATCH_TRIGGER, Map.of())+ : null)),+ request.steps() == null ? List.of() : request.steps(),+ outputSpecFor(request, folder),+ List.of(),+ policyAccessGuard.teamForNewPolicy(),+ null)+ .withSurface(SURFACE);+ try {+ policyValidator.validate(policy);+ } catch (IllegalArgumentException e) {+ if (existing == null) {+ sourceStore.delete(source.id());+ } else if (priorSource != null) {+ sourceStore.save(priorSource);+ }+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());+ }+ Policy saved = policyStore.save(policy);+ policyTriggerManager.notifyPoliciesChanged();+ if (!requestedCreate) {+ // Resuming is a request to catch up: a re-enabled folder sweeps immediately, the+ // way creation does, instead of idling until the next reconcile tick.+ if (saved.enabled() && existing != null && !existing.enabled()) {+ sweepBehindTheResponse(saved);+ }+ return ResponseEntity.ok(toView(saved));+ }+ // Behind the response: holding the POST until every stat, claim and submission+ // finished left the client on a dead spinner. Progress is the runs feed.+ sweepBehindTheResponse(saved);+ return ResponseEntity.accepted().body(toView(saved));+ }++ /**+ * Run the backlog sweep on its own thread. A fresh thread has no security context, so run ids+ * would mint unscoped and vanish from the caller's own runs feed; the caller's name rides the+ * MDC fallback the ownership check reads.+ */+ private void sweepBehindTheResponse(Policy policy) {+ User user = currentUserOrNull();+ String principal = user == null ? null : user.getUsername();+ Thread.startVirtualThread(+ () -> {+ if (principal != null) {+ MDC.put(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY, principal);+ }+ try {+ SweepOutcome outcome = policyRunner.run(policy, SweepKind.USER);+ log.debug(+ "Backlog sweep for {} started {} runs ({} already processed)",+ policy.id(),+ outcome.runIds().size(),+ outcome.alreadyProcessed());+ } catch (RuntimeException e) {+ log.warn("Backlog sweep for {} failed: {}", policy.id(), e.getMessage());+ }+ });+ }++ public record MountedFileView(+ String name,+ long sizeBytes,+ long lastModified,+ /** Its place in the folder's pipeline: done, processing, failed, or waiting. */+ String state,+ boolean hasOriginal) {}++ @GetMapping("/{id}/files")+ @Operation(+ summary = "List a processing folder's files with their pipeline state",+ description =+ "A disk-backed folder reads the directory itself — nothing is mirrored"+ + " into app storage. A storage-backed folder lists its stored"+ + " files. Both carry each file's place in the pipeline, from the"+ + " ledger.")+ public List<MountedFileView> files(@PathVariable String id) {+ User user = currentUserOrNull();+ Policy policy = requireOwn(id, user);+ Path directory = watchedDirectory(policy);+ if (directory == null) {+ return storageFiles(policy);+ }+ // Re-check on read: the permitted roots may have narrowed since the folder was created.+ Path permitted = folderAccessGuard.requirePermitted(directory);+ try (Stream<Path> entries = Files.list(permitted)) {+ List<Path> files =+ entries.filter(Files::isRegularFile)+ .filter(path -> !path.getFileName().toString().startsWith("."))+ // Only files the pipeline can claim; anything else gets no state.+ .filter(ProcessingFolderController::pipelineEligible)+ .toList();+ // The ledger is the per-file truth for in-place processing.+ Path canonicalDir = FolderIdentities.canonicalDir(permitted);+ Map<String, ClaimState> states =+ processedLedger.statesFor(+ policy.id(),+ files.stream()+ .map(f -> FolderIdentities.identity(canonicalDir, permitted, f))+ .toList());+ Path originals = FolderOutputSink.originalsDir(canonicalDir);+ return files.stream()+ .map(+ f ->+ toMountedFile(+ f,+ states.get(+ FolderIdentities.identity(+ canonicalDir, permitted, f)),+ Files.isRegularFile(+ originals.resolve(f.getFileName().toString()))))+ .filter(Objects::nonNull)+ .toList();+ } catch (IOException e) {+ throw new ResponseStatusException(+ HttpStatus.BAD_GATEWAY, "Could not read " + permitted + ": " + e.getMessage());+ }+ }++ private static MountedFileView toMountedFile(Path path, ClaimState state, boolean hasOriginal) {+ try {+ return new MountedFileView(+ path.getFileName().toString(),+ Files.size(path),+ Files.getLastModifiedTime(path).toMillis(),+ stateLabel(state),+ hasOriginal);+ } catch (IOException vanished) {+ return null; // listed then removed; the next read tells the truth+ }+ }++ private static boolean pipelineEligible(Path path) {+ String name = path.getFileName().toString().toLowerCase(Locale.ROOT);+ return DISK_EXTENSIONS.stream().anyMatch(name::endsWith);+ }++ /** The client-facing name of a ledger state; no row means the file is still waiting. */+ private static String stateLabel(ClaimState state) {+ if (state == null) {+ return "waiting";+ }+ return switch (state.status()) {+ case DONE -> "done";+ case ERROR -> "failed";+ case PROCESSING, INTERRUPTED -> "processing";+ };+ }++ /**+ * A storage-backed folder's files, joined to the ledger by the identity the storage source+ * claims by.+ */+ private List<MountedFileView> storageFiles(Policy policy) {+ UUID folderId = storageFolderId(policy);+ if (folderId == null) {+ return List.of();+ }+ List<StoredFile> files =+ storedFileRepository.findAllByFolderId(folderId).stream()+ .filter(+ file ->+ file.getPurpose() == null+ || file.getPurpose() == FilePurpose.GENERIC)+ .toList();+ Map<String, ClaimState> states =+ processedLedger.statesFor(+ policy.id(), files.stream().map(StorageFileIdentities::identity).toList());+ return files.stream()+ .map(+ file ->+ new MountedFileView(+ file.getOriginalFilename(),+ file.getSizeBytes(),+ lastModifiedMillis(file),+ stateLabel(+ states.get(StorageFileIdentities.identity(file))),+ false))+ .toList();+ }++ private static long lastModifiedMillis(StoredFile file) {+ LocalDateTime updatedAt = file.getUpdatedAt();+ return updatedAt == null+ ? 0+ : updatedAt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();+ }++ /** The storage folder a storage-backed processing folder watches; null when disk-backed. */+ private UUID storageFolderId(Policy policy) {+ String sourceId = soleSourceId(policy);+ if (sourceId == null) {+ return null;+ }+ Object raw =+ sourceStore+ .get(sourceId)+ .filter(source -> SOURCE_TYPE.equals(source.type()))+ .map(source -> source.options().get("folderId"))+ .orElse(null);+ if (raw == null) {+ return null;+ }+ try {+ return UUID.fromString(String.valueOf(raw));+ } catch (IllegalArgumentException e) {+ return null;+ }+ }++ /** The disk directory a processing folder watches, or null when it is storage-backed. */+ private Path watchedDirectory(Policy policy) {+ String sourceId = soleSourceId(policy);+ if (sourceId == null) {+ return null;+ }+ return sourceStore+ .get(sourceId)+ .filter(source -> DISK_SOURCE_TYPE.equals(source.type()))+ .map(source -> source.options().get("directory"))+ .filter(Objects::nonNull)+ .map(directory -> Path.of(directory.toString()))+ .orElse(null);+ }++ @PostMapping("/{id}/sweep")+ @Operation(summary = "Run the folder's pipeline against its current contents now")+ public ResponseEntity<SweepOutcome> sweep(@PathVariable String id) {+ User user = currentUserOrNull();+ Policy policy = requireOwn(id, user);+ return ResponseEntity.accepted().body(policyRunner.run(policy, SweepKind.USER));+ }++ public record CancelRunsOutcome(int cancelled) {}++ @PostMapping("/{id}/runs/cancel")+ @Operation(+ summary = "Cancel the folder's in-flight runs",+ description =+ "Pending runs die immediately; a run already inside a tool call finishes"+ + " that call and is discarded without delivering. Cancelled"+ + " files release their claim and read as queued again.")+ public CancelRunsOutcome cancelRuns(@PathVariable String id) {+ User user = currentUserOrNull();+ Policy policy = requireOwn(id, user);+ return new CancelRunsOutcome(policyRunner.cancelRuns(policy.id()));+ }++ /** Per-file retry: the name of the failed file within the folder. */+ public record RetryFileRequest(String name) {}++ @PostMapping("/{id}/files/retry")+ @Operation(+ summary = "Retry one failed file",+ description =+ "Forgets the file's parked failure so it reads as never processed, then"+ + " sweeps so it runs again now. Only the named file is retried:"+ + " the sweep is a light one, which leaves every other parked"+ + " failure parked.")+ public ResponseEntity<SweepOutcome> retryFile(+ @PathVariable String id, @RequestBody RetryFileRequest request) {+ User user = currentUserOrNull();+ Policy policy = requireOwn(id, user);+ if (request == null || request.name() == null || request.name().isBlank()) {+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "a file name is required");+ }+ String name = request.name().trim();+ String identity = identityForName(policy, name);+ if (identity == null || !processedLedger.forgetFailure(policy.id(), identity)) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "'" + name + "' has no failure to retry");+ }+ // Scoped to this identity: only this file's parked failure was forgotten, and claiming+ // any other file would process work nobody asked to retry.+ return ResponseEntity.accepted().body(policyRunner.runFile(policy, identity));+ }++ /** Restore request: the file's name within the folder. */+ public record RevertFileRequest(String name) {}++ @PostMapping("/{id}/files/revert")+ @Operation(+ summary = "Restore a file's archived original",+ description =+ "Moves the pre-processing original kept under .stirling/originals back"+ + " over the processed file. The folder is paused first so"+ + " nothing claims the restored file, and its ledger row is"+ + " forgotten — it reads as waiting until processing resumes."+ + " Disk-backed folders only: storage-backed replacement keeps no"+ + " original.")+ public MountedFileView revertFile(+ @PathVariable String id, @RequestBody RevertFileRequest request) {+ User user = currentUserOrNull();+ Policy policy = requireOwn(id, user);+ if (request == null || request.name() == null || request.name().isBlank()) {+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "a file name is required");+ }+ String name = request.name().trim();+ Path directory = watchedDirectory(policy);+ if (directory == null) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "only a disk-backed folder keeps originals");+ }+ Path permitted = folderAccessGuard.requirePermitted(directory);+ Path target = permitted.resolve(name).normalize();+ if (!permitted.equals(target.getParent())) {+ throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No such file: " + name);+ }+ try {+ Path canonicalDir = FolderIdentities.canonicalDir(permitted);+ Path archived = FolderOutputSink.originalsDir(canonicalDir).resolve(name);+ if (!Files.isRegularFile(archived)) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "'" + name + "' has no original to restore");+ }+ policy = pauseForRevert(policy);+ // The per-row check below cannot see a run mid-delivery, so restore only once the+ // machine is fully quiet.+ if (!policyRunner.quiesced(policy.id())) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT,+ "the folder is processing right now - try again shortly");+ }+ if (!restoreOriginal(policy, permitted, canonicalDir, name)) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "'" + name + "' is being processed right now");+ }+ return toMountedFile(target, null, false);+ } catch (IOException e) {+ throw new ResponseStatusException(+ HttpStatus.BAD_GATEWAY, "Could not restore " + name + ": " + e.getMessage());+ }+ }++ /** Outcome of a folder-wide restore: originals brought back, and files left as-is. */+ public record RevertAllOutcome(int restored, int skipped) {}++ @PostMapping("/{id}/files/revert-all")+ @Operation(+ summary = "Restore every archived original in the folder",+ description =+ "Resets the folder: pauses it, cancels its in-flight runs and waits for"+ + " them to stop, moves each original kept under"+ + " .stirling/originals back over its"+ + " processed file, and forgets the whole processed history —"+ + " failed files included — so everything reads as waiting"+ + " until it resumes. Only files of the watched directory itself"+ + " are touched, and a file mid-run is skipped rather than"+ + " raced.")+ public RevertAllOutcome revertAllFiles(@PathVariable String id) {+ User user = currentUserOrNull();+ Policy policy = requireOwn(id, user);+ Path directory = watchedDirectory(policy);+ if (directory == null) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "only a disk-backed folder keeps originals");+ }+ Path permitted = folderAccessGuard.requirePermitted(directory);+ try {+ Path canonicalDir = FolderIdentities.canonicalDir(permitted);+ policy = pauseForRevert(policy);+ // Stop the machine before moving files: pending runs die, and one mid-tool-call+ // finishes that call — its file is skipped below rather than raced.+ policyRunner.cancelRuns(policy.id());+ // Wait for claims to settle: clearing the ledger before that lets a late settle+ // re-add a row. A run that outruns this wait leaves its file skipped below.+ policyRunner.awaitQuiesce(policy.id(), Duration.ofSeconds(10));+ List<String> names = List.of();+ Path originals = FolderOutputSink.originalsDir(canonicalDir);+ if (Files.isDirectory(originals)) {+ try (Stream<Path> entries = Files.list(originals)) {+ names =+ entries.filter(Files::isRegularFile)+ .map(entry -> entry.getFileName().toString())+ .toList();+ }+ }+ int restored = 0;+ int skipped = 0;+ for (String name : names) {+ if (restoreOriginal(policy, permitted, canonicalDir, name)) {+ restored++;+ } else {+ skipped++;+ }+ }+ // Done and failed rows alike go, so the folder reads as untouched work; only a+ // run that outran the quiesce can re-add a row.+ processedLedger.clearPolicy(policy.id());+ return new RevertAllOutcome(restored, skipped);+ } catch (IOException e) {+ throw new ResponseStatusException(+ HttpStatus.BAD_GATEWAY, "Could not restore originals: " + e.getMessage());+ }+ }++ /** Pause ahead of a restore, or the watch/sweep would claim a restored original as new work. */+ private Policy pauseForRevert(Policy policy) {+ if (!policy.enabled()) {+ return policy;+ }+ Policy paused = policyStore.save(policy.withEnabled(false));+ policyTriggerManager.notifyPoliciesChanged();+ return paused;+ }++ /**+ * Move one archived original back and forget its ledger row so the file reads unprocessed.+ * False when the file is mid-run or the name resolves outside the watched directory.+ */+ private boolean restoreOriginal(Policy policy, Path permitted, Path canonicalDir, String name)+ throws IOException {+ Path target = permitted.resolve(name).normalize();+ if (!permitted.equals(target.getParent())) {+ return false;+ }+ Path archived = FolderOutputSink.originalsDir(canonicalDir).resolve(name);+ String identity = FolderIdentities.identity(canonicalDir, permitted, target);+ ClaimState state = processedLedger.statesFor(policy.id(), List.of(identity)).get(identity);+ if (state != null && state.status() == ProcessedFileStatus.PROCESSING) {+ return false;+ }+ Files.move(+ archived,+ target,+ StandardCopyOption.ATOMIC_MOVE,+ StandardCopyOption.REPLACE_EXISTING);+ processedLedger.forget(policy.id(), identity);+ return true;+ }++ /** The ledger identity of a named file in this folder; null when no such file is listed. */+ private String identityForName(Policy policy, String name) {+ Path directory = watchedDirectory(policy);+ if (directory == null) {+ UUID folderId = storageFolderId(policy);+ if (folderId == null) {+ return null;+ }+ return storedFileRepository.findAllByFolderId(folderId).stream()+ .filter(file -> name.equals(file.getOriginalFilename()))+ .map(StorageFileIdentities::identity)+ .findFirst()+ .orElse(null);+ }+ Path permitted = folderAccessGuard.requirePermitted(directory);+ Path file = permitted.resolve(name).normalize();+ // A name addresses a single entry of the watched directory; anything resolving+ // elsewhere (traversal, an absolute path) is not a file this folder lists.+ if (!permitted.equals(file.getParent())) {+ return null;+ }+ try {+ return FolderIdentities.identity(+ FolderIdentities.canonicalDir(permitted), permitted, file);+ } catch (IOException e) {+ return null;+ }+ }++ @DeleteMapping("/{id}")+ @Operation(+ summary = "Delete a processing folder",+ description =+ "Removes the pipeline and its source. The storage folder and every file in it"+ + " are untouched.")+ public ResponseEntity<Void> delete(@PathVariable String id) {+ User user = currentUserOrNull();+ Policy policy = requireOwn(id, user);+ policyStore.delete(policy.id());+ policy.inputs().stream().map(PipelineInput::sourceId).forEach(sourceStore::delete);+ processedLedger.clearPolicy(policy.id());+ policyTriggerManager.notifyPoliciesChanged();+ return ResponseEntity.noContent().build();+ }++ /**+ * The caller's processing folder already watching the requested place, if any; paths compare+ * normalized, by the platform's own case rules.+ */+ private Policy existingForPlace(SaveProcessingFolderRequest request, User user) {+ boolean onDisk = request.directory() != null && !request.directory().isBlank();+ Path directory = onDisk ? Path.of(request.directory().trim()).normalize() : null;+ return policyAccessGuard.visibleProcessingFolders(policyStore).stream()+ .filter(+ policy -> {+ String sourceId = soleSourceId(policy);+ Source source =+ sourceId == null+ ? null+ : sourceStore.get(sourceId).orElse(null);+ if (source == null) {+ return false;+ }+ if (onDisk) {+ Object watched = source.options().get("directory");+ return watched != null+ && Path.of(watched.toString())+ .normalize()+ .equals(directory);+ }+ return String.valueOf(source.options().get("folderId"))+ .equals(request.folderId());+ })+ .findFirst()+ .orElse(null);+ }++ /** The pair's policy record, only if it is a processing folder the caller owns. */+ private Policy requireOwn(String id, User user) {+ return policyStore+ .get(id)+ .filter(policyAccessGuard::canAccess)+ .filter(ProcessingFolderController::isProcessingFolder)+ .filter(policy -> ownedBy(policy, user))+ .orElseThrow(+ () ->+ new ResponseStatusException(+ HttpStatus.NOT_FOUND, "No processing folder: " + id));+ }++ /** The storage folder, only if the caller owns it — the authorization boundary here. */+ private Folder requireOwnedFolder(String rawFolderId, User user) {+ UUID folderId;+ try {+ folderId = UUID.fromString(String.valueOf(rawFolderId));+ } catch (IllegalArgumentException e) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "a processing folder needs a folderId");+ }+ Folder folder =+ folderRepository+ .findById(folderId)+ .orElseThrow(+ () ->+ new ResponseStatusException(+ HttpStatus.NOT_FOUND, "No folder: " + rawFolderId));+ if (folder.getOwner() == null || !Objects.equals(folder.getOwner().getId(), user.getId())) {+ throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No folder: " + rawFolderId);+ }+ return folder;+ }++ /**+ * Per-user scoping on top of the guard's team scoping: processing folders are personal. Login+ * disabled (null owner) matches everything.+ */+ private static boolean ownedBy(Policy policy, User user) {+ if (user == null) {+ // No accounts on this install: the local operator owns everything.+ return true;+ }+ return policy.owner() == null || Objects.equals(policy.owner(), user.getUsername());+ }++ /**+ * The caller, or null on an install with no accounts, where the local operator is the only user+ * — requiring a principal would 401 the whole surface there.+ */+ private User currentUserOrNull() {+ if (!applicationProperties.getSecurity().isEnableLogin()) {+ return null;+ }+ return fileStorageService.requireAuthenticatedUser();+ }++ /** The pair's source id; the compose invariant is exactly one source per processing folder. */+ private static String soleSourceId(Policy policy) {+ return policy.inputs().isEmpty() ? null : policy.inputs().get(0).sourceId();+ }++ /** Whether a policy record belongs to this surface (and so is hidden from the others). */+ public static boolean isProcessingFolder(Policy policy) {+ return SURFACE.equals(policy.surface());+ }++ /**+ * Pinned to {@code track}: claim each file once per version and leave it where the user put it+ * — the disk source's default mode deletes processed files, which a processing folder must+ * never do.+ */+ private static Map<String, Object> diskSourceOptions(String directory) {+ return Map.of(+ "directory",+ directory.trim(),+ "mode",+ "track",+ // Stat identity, not hash: hashing would touch every file before the first run+ // starts. A re-touched file reprocessing is the right trade.+ "identity",+ "stat",+ "recursive",+ false,+ // Only documents the pipeline accepts: zips and installers would burn sweep+ // budget on doomed runs.+ "extensions",+ DISK_EXTENSIONS,+ "limit",+ DISK_SWEEP_LIMIT);+ }++ /** The trailing path segment ("Downloads"), or the raw path when it has none. */+ private static String diskFolderName(String directory) {+ Path path = Path.of(directory.trim());+ Path fileName = path.getFileName();+ return fileName == null ? path.toString() : fileName.toString();+ }++ /**+ * 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+ * claim the same way, so a sweep never mistakes the folder's own output for new work. Disk+ * output is what works on an install with no accounts and no file storage.+ */+ private OutputSpec outputSpecFor(SaveProcessingFolderRequest request, Folder folder) {+ Map<String, Object> options =+ new HashMap<>(request.output() == null ? Map.of() : request.output());+ if (folder != null) {+ // Force the output to the caller-owned source folder: the storage sink only checks a+ // folderId exists, not that the caller owns it, so honouring a request-supplied one+ // would write output into another tenant's folder. Processing is in place anyway.+ options.put("folderId", folder.getId().toString());+ return new OutputSpec("storage", options);+ }+ options.put("directory", request.directory().trim());+ options.put("replace", true);+ return new OutputSpec("folder", options);+ }++ /**+ * What the folder watches comes from its source, never its output — the output may name a+ * results subdirectory, which is not the folder's address.+ */+ private ProcessingFolderView toView(Policy policy) {+ Map<String, Object> output = new HashMap<>(policy.output().options());+ output.remove(SURFACE_OPTION);+ String sourceId = soleSourceId(policy);+ Source source = sourceId == null ? null : sourceStore.get(sourceId).orElse(null);+ Object folderId = source == null ? null : source.options().get("folderId");+ Object directory = source == null ? null : source.options().get("directory");+ return new ProcessingFolderView(+ policy.id(),+ folderId == null ? null : folderId.toString(),+ directory == null ? null : directory.toString(),+ policy.name(),+ policy.enabled(),+ policy.steps(),+ output);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.javaindex f9c0f719ef..e9656e55d2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java@@ -7,6 +7,7 @@ import java.util.List;import java.util.UUID;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;+import java.util.concurrent.Semaphore;import org.slf4j.MDC;import org.springframework.core.io.Resource;@@ -70,7 +71,7 @@ public class PolicyEngine {// errorCode marking a run that was never admitted (job queue full under load). Transient: the// client treats it as "busy" and retries, rather than as a terminal processing failure.- private static final String QUEUE_FULL_CODE = "POLICY_QUEUE_FULL";+ static final String QUEUE_FULL_CODE = "POLICY_QUEUE_FULL";private final PolicyExecutor stepExecutor;private final TaskManager taskManager;@@ -123,11 +124,8 @@ public class PolicyEngine {PolicyInputs inputs,PolicyProgressListener listener,String policyId) {- // Ad-hoc run (no stored policy): bill whoever kicked it off and own the outputs as them- // too.- // Capture the principal on this (request) thread — it does not survive the hop onto the- // async- // worker.+ // Ad-hoc run (no stored policy): bill whoever kicked it off and own its outputs as them.+ // Captured on this request thread, which the async worker does not inherit.String principal = currentActingPrincipal();return submitForPrincipal(principal,@@ -138,6 +136,7 @@ public class PolicyEngine {inputs,listener,null,+ null,null);}@@ -160,6 +159,20 @@ public class PolicyEngine {PolicyProgressListener listener,String sourceId,String fileIdentity) {+ return runPolicy(policy, inputs, listener, sourceId, fileIdentity, null);+ }++ /**+ * As above, pacing execution through {@code admission}: runs register immediately (pending) but+ * execute only while holding a permit. Null means ungated.+ */+ public PolicyRunHandle runPolicy(+ Policy policy,+ PolicyInputs inputs,+ PolicyProgressListener listener,+ String sourceId,+ String fileIdentity,+ Semaphore admission) {// Bill the policy owner: trigger-fired runs have no security context, and the async worker// doesn't inherit the caller's, so the owner (stamped at policy creation) is the reliable// billing identity — and for org-wide policies the org/owner is meant to pay. But own the@@ -193,7 +206,8 @@ public class PolicyEngine {resolved,listener,sourceId,- fileIdentity);+ fileIdentity,+ admission);}private PolicyRunHandle submitForPrincipal(@@ -205,7 +219,8 @@ public class PolicyEngine {PolicyInputs inputs,PolicyProgressListener listener,String sourceId,- String fileIdentity) {+ String fileIdentity,+ Semaphore admission) {// Scope the run id to the current user (this request thread) so the file-download// ownership check passes. No-op when security is off.String runId = jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString());@@ -230,7 +245,27 @@ public class PolicyEngine {billingPrincipal,fileOwner,definition.name(),- () -> runToCompletion(run, inputs, tracking, completion));+ () -> {+ // Pacing gate: park (cheap on a virtual thread, and the run+ // honestly reads as pending) until a slot frees up.+ if (admission != null) {+ try {+ admission.acquire();+ } catch (InterruptedException e) {+ // Shutdown while parked: never ran, never will.+ Thread.currentThread().interrupt();+ completion.completeExceptionally(e);+ return;+ }+ }+ try {+ runToCompletion(run, inputs, tracking, completion);+ } finally {+ if (admission != null) {+ admission.release();+ }+ }+ });// One admission unit per run; steps run synchronously within it, so this gates heavy work// without the pool-within-pool risk of queueing each tool call.@@ -270,6 +305,28 @@ public class PolicyEngine {return cancelled;}+ /**+ * Cancel every non-terminal run of one policy; returns how many transitioned. Pending runs die+ * before starting; one inside a tool call finishes that call, then settles as cancelled.+ */+ public int cancelAllFor(String policyId) {+ int cancelled = 0;+ for (PolicyRun run : registry.all()) {+ if (policyId.equals(run.getPolicyId()) && run.cancel()) {+ taskManager.addNote(run.getRunId(), "Run cancelled by revert");+ cancelled++;+ }+ }+ return cancelled;+ }++ /** Whether any run of this policy has not yet reached a terminal state. */+ public boolean hasActiveRuns(String policyId) {+ return registry.all().stream()+ .anyMatch(+ run -> policyId.equals(run.getPolicyId()) && !run.getStatus().isTerminal());+ }+/** Resume a run paused in {@code WAITING_FOR_INPUT}. Not yet implemented. */public String resume(String runId, List<Resource> additionalInputs) {throw new UnsupportedOperationException("Pause/resume is not yet implemented");@@ -286,9 +343,18 @@ public class PolicyEngine {// a single charge, and two separate policy runs on the same document stay distinct charges.try (AutomationRunContext.Scope runScope = AutomationRunContext.open(runId)) {try {- run.markRunning();+ if (!run.markRunning()) {+ // Cancelled before it started: nothing runs, nothing delivers.+ return;+ }PolicyExecutionResult result =stepExecutor.execute(run.getDefinition(), inputs, listener);+ if (!run.beginDelivery()) {+ // Cancelled while the steps ran: discard the produced files —+ // delivering would stamp results over files being restored right now.+ taskManager.addNote(runId, "Cancelled before delivery; results discarded");+ return;+ }// Deliver the run's files to every destination; no destinations means inline// delivery (results stored/returned to the caller), preserving ad-hoc/AI behaviour.List<OutputSpec> destinations = run.getDefinition().outputs();@@ -300,7 +366,7 @@ public class PolicyEngine {outputs.addAll(sinkFor(destination).deliver(- new OutputDelivery(runId, run.getPolicyId()),+ new OutputDelivery(runId, run.getPolicyId(), inputs),result.files(),destination));}@@ -476,7 +542,7 @@ public class PolicyEngine {* controller audit aspect on request threads). We reuse it to carry the billing identity onto* the policy worker thread.*/- private static final String AUDIT_PRINCIPAL_MDC_KEY = "auditPrincipal";+ public static final String AUDIT_PRINCIPAL_MDC_KEY = "auditPrincipal";/*** The username to bill an ad-hoc run to, captured on the submitting (request) thread. Prefersdiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.javaindex d159ebf012..5a3d05a199 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java@@ -1,8 +1,10 @@package stirling.software.proprietary.policy.engine;import java.io.IOException;+import java.time.Duration;import java.util.ArrayList;import java.util.List;+import java.util.concurrent.Semaphore;import java.util.function.Consumer;import org.springframework.stereotype.Service;@@ -10,6 +12,8 @@ import org.springframework.stereotype.Service;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;+import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.config.PolicyAccessGuard;import stirling.software.proprietary.policy.input.InputSource;import stirling.software.proprietary.policy.input.ResolvedInput;import stirling.software.proprietary.policy.ledger.ProcessedLedger;@@ -42,6 +46,17 @@ public class PolicyRunner {private final SourceStore sourceStore;private final SourceDocCounter docCounter;private final ProcessedLedger processedLedger;+ private final ApplicationProperties applicationProperties;+ private final PolicyAccessGuard policyAccessGuard;++ /**+ * One admission gate per sweep: every run is visible immediately, but only this many execute at+ * once, so completions arrive steadily from the first file onward.+ */+ private Semaphore sweepAdmission() {+ int concurrency = applicationProperties.getPolicies().getSweepConcurrency();+ return concurrency > 0 ? new Semaphore(concurrency) : null;+ }/** Full-listing sweep over every input: resolve each source, then reconcile the ledger. */public SweepOutcome run(Policy policy) {@@ -62,25 +77,54 @@ public class PolicyRunner {return run(policy, List.of(input), sweep);}+ /**+ * Run one named file of the policy and nothing else: a per-file retry, where claiming the+ * folder's other files would process work the user did not ask for - including an original they+ * just restored, whose ledger row the restore deliberately forgot.+ */+ public SweepOutcome runFile(Policy policy, String identity) {+ return run(policy, policy.inputs(), SweepKind.LIGHT, identity);+ }++ /** Sweep every one of the given inputs, claiming whatever each source offers. */+ public SweepOutcome run(Policy policy, List<PipelineInput> inputs, SweepKind sweep) {+ return run(policy, inputs, sweep, null);+ }+/*** Core sweep: pulls each of the given inputs' sources; each yielded unit becomes its own run so* one failure does not affect the others. No inputs means one run with no input (generator* pipeline). Missing or disabled sources are skipped so one broken reference does not stop the* rest. Presence cleanup only runs when the sweep covered every input of the policy - a- * single-binding fire cannot reconcile the whole policy's ledger. Returns the ids of the runs- * it started plus what the sweep skipped, so a manual trigger can report which runs to follow- * or why nothing ran.+ * single-binding fire cannot reconcile the whole policy's ledger. A non-null {@code target}+ * narrows the sweep to that one ledger identity. Returns the ids of the runs it started plus+ * what the sweep skipped, so a manual trigger can report which runs to follow or why nothing+ * ran.*/- public SweepOutcome run(Policy policy, List<PipelineInput> inputs, SweepKind sweep) {+ private SweepOutcome run(+ Policy policy, List<PipelineInput> inputs, SweepKind sweep, String target) {+ if (policyAccessGuard.isOrphaned(policy)) {+ // Reachable by nobody, so nobody could stop it: running would replace files in place+ // in a folder no user can list, pause, revert, or delete.+ log.warn("Processing folder {} has no reachable owner; not sweeping it", policy.id());+ return new SweepOutcome(List.of(), 0, 0, 0, 0, 0);+ }long sweepStart = System.currentTimeMillis();- PolicySweep context = new PolicySweep(policy.id(), sweep, processedLedger);+ PolicySweep context = new PolicySweep(policy.id(), sweep, processedLedger, target);+ Semaphore admission = sweepAdmission();List<String> runIds = new ArrayList<>();if (inputs.isEmpty()) {- // Generator pipeline: one run with no input. Still fall through to the cleanup- // below so rows recorded for its folder outputs are pruned like anything else,- // instead of accumulating until the policy is deleted.- // Generator pipeline: no input, so neither a source nor a document to attribute to.- runIds.add(startRun(policy, null, null, PolicyInputs.of(List.of()), unused -> {}));+ // Generator pipeline: one run with no input, so neither a source nor a document to+ // attribute to. Still falls through to the cleanup below, so rows recorded for its+ // folder outputs are pruned instead of accumulating until the policy is deleted.+ runIds.add(+ startRun(+ policy,+ null,+ null,+ PolicyInputs.of(List.of()),+ unused -> {},+ admission));}for (PipelineInput input : inputs) {String sourceId = input.sourceId();@@ -100,7 +144,7 @@ public class PolicyRunner {context.vetoCleanup();continue;}- runIds.addAll(pullAndRun(policy, sourceId, source.toInputSpec(), context));+ runIds.addAll(pullAndRun(policy, sourceId, source.toInputSpec(), context, admission));}boolean fullPolicy = inputs.size() == policy.inputs().size();if (fullPolicy && context.cleanupAllowed()) {@@ -141,13 +185,48 @@ public class PolicyRunner {return policyEngine.submit(definition, inputs, listener);}+ /** Whether nothing of the policy is running or mid-settle — safe to move its files. */+ public boolean quiesced(String policyId) {+ return !policyEngine.hasActiveRuns(policyId) && !processedLedger.anyInFlight(policyId);+ }++ /** Cancel every non-terminal run of the policy (see {@link PolicyEngine#cancelAllFor}). */+ public int cancelRuns(String policyId) {+ return policyEngine.cancelAllFor(policyId);+ }++ /**+ * Wait until every run of the policy has settled its claim: none outside a terminal state, no+ * ledger row in flight. False on timeout — a run inside a long tool call can outlive any+ * reasonable request budget.+ */+ public boolean awaitQuiesce(String policyId, Duration timeout) {+ long deadline = System.currentTimeMillis() + timeout.toMillis();+ while (policyEngine.hasActiveRuns(policyId) || processedLedger.anyInFlight(policyId)) {+ if (System.currentTimeMillis() >= deadline) {+ return false;+ }+ try {+ Thread.sleep(150);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return false;+ }+ }+ return true;+ }+/*** Resolves the source and starts a run per unit; records how many documents the source fed and* returns the ids of the runs started. Any source that could not be listed completely vetoes* this sweep's ledger cleanup.*/private List<String> pullAndRun(- Policy policy, String sourceId, InputSpec spec, PolicySweep context) {+ Policy policy,+ String sourceId,+ InputSpec spec,+ PolicySweep context,+ Semaphore admission) {InputSource source = sourceFor(spec);if (source == null) {log.warn(@@ -181,7 +260,8 @@ public class PolicyRunner {sourceId,unit.fileIdentity(),unit.inputs(),- unit.onComplete()));+ unit.onComplete(),+ admission));docsFed += unit.inputs().primary().size();}docCounter.record(sourceId, docsFed);@@ -193,13 +273,39 @@ public class PolicyRunner {String sourceId,String fileIdentity,PolicyInputs inputs,- Consumer<Boolean> onComplete) {+ Consumer<Boolean> onComplete,+ Semaphore admission) {log.info("Running policy {} ({})", policy.id(), policy.name());PolicyRunHandle handle =policyEngine.runPolicy(- policy, inputs, PolicyProgressListener.NOOP, sourceId, fileIdentity);+ policy,+ inputs,+ PolicyProgressListener.NOOP,+ sourceId,+ fileIdentity,+ admission);handle.completion()- .whenComplete((run, throwable) -> onComplete.accept(succeeded(run, throwable)));+ .whenComplete(+ (run, throwable) -> {+ boolean cancelled =+ run != null && run.getStatus() == PolicyRunStatus.CANCELLED;+ boolean neverAdmitted =+ run != null+ && PolicyEngine.QUEUE_FULL_CODE.equals(+ run.getErrorCode());+ if (cancelled || neverAdmitted) {+ // Neither is a verdict on the file: cancellation is the+ // user's intent, and queue-full means nothing was attempted.+ // Settle, then drop the row, so the file reads as queued and+ // the next sweep takes it again.+ onComplete.accept(false);+ if (fileIdentity != null) {+ processedLedger.forget(policy.id(), fileIdentity);+ }+ return;+ }+ onComplete.accept(succeeded(run, throwable));+ });return handle.runId();}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.javaindex 469b5f769e..2ad5cdb4b7 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.java@@ -24,6 +24,10 @@ final class PolicySweep implements ResolveContext {private final String policyId;private final SweepKind kind;private final ProcessedLedger ledger;++ /** When set, the only identity this sweep may claim; null sweeps the whole policy. */+ private final String target;+private final Set<String> present = new HashSet<>();// Claim states loaded in bulk at reportPresent; a claim outside the prefetch falls back to a// single lookup. A stale entry cannot double-claim (the ledger re-checks every transition),@@ -31,19 +35,39 @@ final class PolicySweep implements ResolveContext {private final Map<String, ClaimState> prefetched = new HashMap<>();private final Set<String> prefetchedIdentities = new HashSet<>();private boolean cleanupVetoed;+ private int retried;- PolicySweep(String policyId, SweepKind kind, ProcessedLedger ledger) {+ PolicySweep(String policyId, SweepKind kind, ProcessedLedger ledger, String target) {this.policyId = policyId;this.kind = kind;this.ledger = ledger;+ this.target = target;}@Overridepublic synchronized boolean claim(String identity, String gate, Supplier<String> contentHash) {+ // Refused here rather than after resolve: the sources still list normally, but a capped+ // listing would otherwise spend its whole budget claiming other files and never reach the+ // one file that was asked for.+ if (target != null && !target.equals(identity)) {+ return false;+ }ClaimState observed =prefetchedIdentities.contains(identity)? prefetched.get(identity): ledger.statesFor(policyId, List.of(identity)).get(identity);+ // A user-invoked sweep retries parked failures: the click usually follows fixing+ // whatever failed them, and only the unattended watcher owes a poison file caution.+ if (kind == SweepKind.USER+ && observed != null+ && observed.status() == ProcessedFileStatus.ERROR+ && gate.equals(observed.gate())+ && ledger.reclaimFailed(policyId, identity, gate)) {+ retried++;+ prefetchedIdentities.add(identity);+ prefetched.put(identity, new ClaimState(ProcessedFileStatus.PROCESSING, gate, null));+ return true;+ }boolean claimed = ledger.claim(policyId, identity, gate, contentHash, observed);if (claimed) {// A nested source surfacing the same file later in this sweep sees it in flight@@ -68,7 +92,7 @@ final class PolicySweep implements ResolveContext {@Overridepublic synchronized void reportPresent(Collection<String> identities) {- if (kind == SweepKind.FULL) {+ if (kind != SweepKind.LIGHT) {present.addAll(identities);}prefetched.putAll(ledger.statesFor(policyId, identities));@@ -80,7 +104,7 @@ final class PolicySweep implements ResolveContext {}synchronized boolean cleanupAllowed() {- return kind == SweepKind.FULL && !cleanupVetoed;+ return kind != SweepKind.LIGHT && !cleanupVetoed;}synchronized Set<String> presentIdentities() {@@ -112,6 +136,7 @@ final class PolicySweep implements ResolveContext {present.size(),alreadyProcessed,parked,- Math.max(0, processing - runIds.size()));+ Math.max(0, processing - runIds.size()),+ retried);}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.javaindex c2455749ae..423c25e54c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.java@@ -2,9 +2,12 @@ package stirling.software.proprietary.policy.engine;/*** How thorough a policy sweep is: {@link #FULL} (complete listing; also stamps presence and prunes- * the ledger) or {@link #LIGHT} (event-driven; claims only, cost proportional to what changed).+ * the ledger), {@link #LIGHT} (event-driven; claims only, cost proportional to what changed), or+ * {@link #USER} (a person asked — a full sweep that also retries files parked by an earlier+ * failure, since the click usually follows fixing whatever failed them).*/public enum SweepKind {FULL,- LIGHT+ LIGHT,+ USER}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepOutcome.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepOutcome.javaindex 752299976d..3bc522eb48 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepOutcome.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepOutcome.java@@ -11,7 +11,13 @@ import java.util.List;* listing.*/public record SweepOutcome(- List<String> runIds, int filesListed, int alreadyProcessed, int parked, int inFlight) {+ List<String> runIds,+ int filesListed,+ int alreadyProcessed,+ int parked,+ int inFlight,+ /** Files this sweep took on again after an earlier failure (user sweeps only). */+ int retried) {public SweepOutcome {runIds = runIds == null ? List.of() : List.copyOf(runIds);diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.javaindex 1e07185ab5..e4d8ada9aa 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java@@ -9,7 +9,10 @@ import java.nio.file.Path;import java.nio.file.SimpleFileVisitor;import java.nio.file.attribute.BasicFileAttributes;import java.util.ArrayList;+import java.util.Collection;+import java.util.Comparator;import java.util.List;+import java.util.Locale;import java.util.Map;import java.util.function.Supplier;import java.util.stream.Stream;@@ -32,11 +35,15 @@ import stirling.software.proprietary.policy.model.PolicyInputs;* {@link ResolveContext} ledger rather than moved aside, so nothing accumulates in a work* directory. Options: "mode" is "consume" (default: a processed file is removed once every policy* that claimed it has settled successfully and it is still the version that ran; failures stay in- * place and are not retried until they change) or "snapshot" (stateless, every run sees the full- * set); "recursive" descends into subdirectories; "identity" is "stat" (default, any size/mtime- * change is a new version) or "hash" (content-verified, so a touch does not reprocess). Hidden- * files and directories, including the legacy {@code .stirling} work dir, are never picked up, and- * files mid-write are skipped by the readiness check.+ * place and are not retried until they change), "track" (the same claim-once-per-version tracking+ * with no removal, for a directory the user owns and expects to stay intact - their Downloads, a+ * scanner drop), or "snapshot" (stateless, every run sees the full set); "recursive" descends into+ * subdirectories; "identity" is "stat" (default, any size/mtime change is a new version) or "hash"+ * (content-verified, so a touch does not reprocess); "extensions" restricts the sweep to files with+ * one of the given suffixes (dot optional, case-insensitive) - anything else in the directory is+ * entirely out of scope, not a skipped failure. Hidden files and directories, including the legacy+ * {@code .stirling} work dir, are never picked up, and files mid-write are skipped by the readiness+ * check.*/@Slf4j@Service@@ -81,6 +88,22 @@ public class FolderInputSource implements InputSource {}Path canonicalDir = FolderIdentities.canonicalDir(inputDir);List<Path> present = listFiles(inputDir, config.recursive());+ // Filtered before anything observes the listing: an out-of-scope file is invisible to the+ // ledger and the sweep alike, so it neither burns the sweep limit nor parks as a failure.+ if (!config.extensions().isEmpty()) {+ present.removeIf(+ file ->+ config.extensions().stream()+ .noneMatch(+ ext ->+ file.getFileName()+ .toString()+ .toLowerCase(Locale.ROOT)+ .endsWith(ext)));+ }+ // Newest first: a capped sweep must spend its budget on what the user most recently added,+ // not on whichever old files sort first. Unreadable mtimes sort oldest and are taken last.+ present.sort(Comparator.comparingLong(FolderInputSource::mtimeForOrdering).reversed());if (config.snapshot()) {List<ResolvedInput> work = new ArrayList<>();@@ -99,6 +122,16 @@ public class FolderInputSource implements InputSource {List<ResolvedInput> work = new ArrayList<>();for (Path file : present) {+ // "limit" caps how much one sweep takes on, not what it observes: the full listing is+ // reported above, and files beyond the cap keep their rows for later sweeps.+ if (config.limit() > 0 && work.size() >= config.limit()) {+ log.debug(+ "Folder {} has more ready files than this sweep's limit of {}; the rest"+ + " follow on later sweeps",+ inputDir,+ config.limit());+ break;+ }if (!readinessChecker.isReady(file)) {continue;}@@ -117,17 +150,43 @@ public class FolderInputSource implements InputSource {if (!claimed) {continue;}+ String claimedGate = gate;work.add(ResolvedInput.forFile(PolicyInputs.of(List.of(fileResource(file))),identity,- success ->- completeConsumed(- ctx, identity, file, gate, contentHash, success)));+ success -> {+ if (config.track()) {+ // Track mode never removes the input. A success settles at+ // the file's CURRENT version: an in-place pipeline replaces+ // the input with its result, and the claimed version would+ // leave the folder re-processing its own output forever.+ ctx.settle(+ identity,+ success ? currentGate(file, claimedGate) : claimedGate,+ null,+ success);+ return;+ }+ completeConsumed(+ ctx, identity, file, claimedGate, contentHash, success);+ }));}+ // Within the batch, smallest first: the sweep's first results should appear within+ // seconds of it starting, not after its largest document.+ work.sort(Comparator.comparingLong(FolderInputSource::workSize));return work;}+ /** The file's stat gate as it is now; the claimed gate when it cannot be read. */+ private static String currentGate(Path file, String claimedGate) {+ try {+ return FolderIdentities.statGate(file);+ } catch (IOException gone) {+ return claimedGate;+ }+ }+/*** Settle at the version this run claimed - never a re-read, so a file replaced mid-run reads as* a new unclaimed version next sweep instead of being marked processed. Then remove the input@@ -209,6 +268,26 @@ public class FolderInputSource implements InputSource {}/** Every non-hidden regular file in the source, readable or not. */+ /** The file's mtime for selection ordering; unreadable sorts oldest, taken last. */+ private static long mtimeForOrdering(Path file) {+ try {+ return Files.getLastModifiedTime(file).toMillis();+ } catch (IOException e) {+ return Long.MIN_VALUE;+ }+ }++ /** A claimed unit's primary size, for run ordering; unknown sorts last. */+ private static long workSize(ResolvedInput unit) {+ try {+ return unit.inputs().primary().isEmpty()+ ? Long.MAX_VALUE+ : unit.inputs().primary().get(0).contentLength();+ } catch (IOException e) {+ return Long.MAX_VALUE;+ }+ }+private static List<Path> listFiles(Path inputDir, boolean recursive) throws IOException {List<Path> files = new ArrayList<>();if (!recursive) {@@ -271,15 +350,25 @@ public class FolderInputSource implements InputSource {};}- record FolderConfig(Path directory, boolean snapshot, boolean recursive, boolean hashIdentity) {+ record FolderConfig(+ Path directory,+ boolean snapshot,+ boolean track,+ boolean recursive,+ boolean hashIdentity,+ int limit,+ List<String> extensions) {private static final String DIRECTORY_OPTION = "directory";private static final String MODE_OPTION = "mode";private static final String MODE_SNAPSHOT = "snapshot";+ private static final String MODE_TRACK = "track";private static final String RECURSIVE_OPTION = "recursive";private static final String IDENTITY_OPTION = "identity";private static final String IDENTITY_STAT = "stat";private static final String IDENTITY_HASH = "hash";+ private static final String LIMIT_OPTION = "limit";+ private static final String EXTENSIONS_OPTION = "extensions";static FolderConfig from(Map<String, Object> options) {Object directory = options.get(DIRECTORY_OPTION);@@ -288,6 +377,7 @@ public class FolderInputSource implements InputSource {}Object mode = options.get(MODE_OPTION);boolean snapshot = mode != null && MODE_SNAPSHOT.equals(mode.toString());+ boolean track = mode != null && MODE_TRACK.equals(mode.toString());Object recursive = options.get(RECURSIVE_OPTION);boolean recurse = recursive != null && Boolean.parseBoolean(recursive.toString());Object identity = options.get(IDENTITY_OPTION);@@ -298,7 +388,28 @@ public class FolderInputSource implements InputSource {throw new IllegalArgumentException("folder input 'identity' must be 'stat' or 'hash'");}- return new FolderConfig(Path.of(directory.toString()), snapshot, recurse, hash);+ Object limit = options.get(LIMIT_OPTION);+ int max = 0;+ if (limit != null && !limit.toString().isBlank()) {+ try {+ max = Math.max(0, Integer.parseInt(limit.toString().trim()));+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException("folder input 'limit' must be a number", e);+ }+ }+ List<String> extensions = List.of();+ if (options.get(EXTENSIONS_OPTION) instanceof Collection<?> values) {+ extensions =+ values.stream()+ .map(String::valueOf)+ .map(String::trim)+ .filter(value -> !value.isEmpty())+ .map(value -> value.startsWith(".") ? value : "." + value)+ .map(value -> value.toLowerCase(Locale.ROOT))+ .toList();+ }+ return new FolderConfig(+ Path.of(directory.toString()), snapshot, track, recurse, hash, max, extensions);}}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.javaindex 1b10ff3a06..94b882508f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/ResolvedInput.java@@ -2,7 +2,6 @@ package stirling.software.proprietary.policy.input;import java.util.function.Consumer;-import stirling.software.proprietary.policy.ledger.IdentityHasher;import stirling.software.proprietary.policy.model.PolicyInputs;/**@@ -10,9 +9,9 @@ import stirling.software.proprietary.policy.model.PolicyInputs;* with the run's success (e.g. a folder source routes the input to done/error). A source may return* several of these, one per file.*- * @param fileIdentity stable opaque reference to the document, or null when the source has none.- * Always hashed, never the source's own identity: a folder identity is a path, and a path is a- * filename. See {@link #forFile}.+ * @param fileIdentity stable reference to the document — the source's own identity for it, or null+ * when the source has none. Name-shaped by design: a run displays the file it is processing by+ * it, and the ledger resolves it when a claim is released.*/public record ResolvedInput(PolicyInputs inputs, String fileIdentity, Consumer<Boolean> onComplete) {@@ -22,16 +21,16 @@ public record ResolvedInput(}/**- * One document, referenced by the hash of the source's identity for it. Stable across sweeps,- * which is what lets the same broken file fold into one incident instead of opening a fresh one- * every time the source re-lists it.+ * One document, referenced by the source's own identity for it. Stable across sweeps, which is+ * what lets the same broken file fold into one incident instead of opening a fresh one every+ * time the source re-lists it. Deliberately not hashed: the identity is name-shaped (a folder's+ * is the document's path), which is exactly what lets a live run be shown by the file it is+ * processing — and the run feed already carries the delivered outputs' real paths, so hashing+ * the input hid nothing.*/public static ResolvedInput forFile(PolicyInputs inputs, String identity, Consumer<Boolean> onComplete) {- return new ResolvedInput(- inputs,- identity == null ? null : IdentityHasher.identityHash(identity),- onComplete);+ return new ResolvedInput(inputs, identity, onComplete);}/** No document reference and no completion side effect. */diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.javanew file mode 100644index 0000000000..53bf031b9a--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java@@ -0,0 +1,199 @@+package stirling.software.proprietary.policy.input;++import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.List;+import java.util.UUID;++import org.springframework.core.io.AbstractResource;+import org.springframework.stereotype.Service;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.ledger.StorageFileIdentities;+import stirling.software.proprietary.policy.model.InputSpec;+import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.storage.model.FilePurpose;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.storage.repository.FolderRepository;+import stirling.software.proprietary.storage.repository.StoredFileRepository;++/**+ * Reads input files from a folder in app storage — the input side of a processing folder. Each+ * stored file is claimed through the ledger at its current content version ({@code updatedAt} ++ * size): unchanged files never rerun, re-uploaded or edited ones run again, nothing is deleted. An+ * in-place output bumps that version, and the completion hook settles the ledger at the post-run+ * version so the next sweep does not re-ingest the run's own output.+ *+ * <p>Options: {@code folderId} — the storage folder's UUID.+ */+@Slf4j+@Service+@RequiredArgsConstructor+public class StorageFolderInputSource implements InputSource {++ private static final String TYPE = "storage-folder";++ private final StoredFileRepository storedFileRepository;+ private final FolderRepository folderRepository;+ private final StorageProvider storageProvider;+ private final ApplicationProperties applicationProperties;++ @Override+ public String type() {+ return TYPE;+ }++ @Override+ public boolean supports(InputSpec spec) {+ return spec != null && TYPE.equals(spec.type());+ }++ /** Fails fast at save time: storage must be on and the folder must exist. */+ @Override+ public void validate(InputSpec spec) {+ if (!applicationProperties.getSecurity().isEnableLogin()+ || !applicationProperties.getStorage().isEnabled()) {+ throw new IllegalArgumentException("file storage is not enabled on this server");+ }+ if (!folderRepository.existsById(folderId(spec))) {+ throw new IllegalArgumentException(+ "unknown storage folder: " + spec.options().get("folderId"));+ }+ }++ @Override+ public List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {+ UUID folderId = folderId(spec);+ List<StoredFile> files =+ storedFileRepository.findAllByFolderId(folderId).stream()+ .filter(StorageFolderInputSource::ingestible)+ .toList();++ ctx.reportPresent(files.stream().map(StorageFolderInputSource::identity).toList());++ List<ResolvedInput> work = new ArrayList<>();+ for (StoredFile file : files) {+ String identity = identity(file);+ String gate = gate(file);+ // The hash tier turns metadata-only gate bumps (a folder move, a rename) into a gate+ // refresh instead of a reprocess; only genuinely new content runs again.+ if (!ctx.claim(+ identity,+ gate,+ () -> StorageFileIdentities.contentHash(storageProvider, file))) {+ continue;+ }+ Long fileId = file.getId();+ work.add(+ new ResolvedInput(+ PolicyInputs.of(List.of(new StoredFileResource(storageProvider, file))),+ identity,+ success ->+ settleAtCurrentVersion(ctx, fileId, identity, gate, success)));+ }+ return work;+ }++ /**+ * Settle at the file's post-run version, not the claimed one — an in-place output bumped {@code+ * updatedAt}, and the old gate would read it as a fresh edit. A file deleted mid-run settles at+ * the claimed gate; presence cleanup prunes its row.+ */+ private void settleAtCurrentVersion(+ ResolveContext ctx, Long fileId, String identity, String claimedGate, boolean success) {+ StoredFile current = storedFileRepository.findById(fileId).orElse(null);+ if (current == null) {+ ctx.settle(identity, claimedGate, null, success);+ return;+ }+ // Settle with the content hash so a later metadata-only bump (move/rename) refreshes the+ // gate instead of reprocessing. Hash failures fall back to gate-only semantics.+ String finalContentHash = null;+ try {+ finalContentHash = StorageFileIdentities.contentHash(storageProvider, current);+ } catch (RuntimeException e) {+ log.debug("Could not hash {} at settle: {}", identity, e.getMessage());+ }+ ctx.settle(identity, gate(current), finalContentHash, success);+ }++ /** Only generic user files are processed — purpose-bound artifacts belong to their feature. */+ private static boolean ingestible(StoredFile file) {+ return file.getPurpose() == null || file.getPurpose() == FilePurpose.GENERIC;+ }++ private static String identity(StoredFile file) {+ return StorageFileIdentities.identity(file);+ }++ private static String gate(StoredFile file) {+ return StorageFileIdentities.gate(file);+ }++ private static UUID folderId(InputSpec spec) {+ Object raw = spec.options().get("folderId");+ try {+ return UUID.fromString(String.valueOf(raw));+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException("storage-folder source needs a folderId", e);+ }+ }++ /**+ * Streams the stored blob on demand, presenting the user-visible filename. Content is not+ * version-pinned: a concurrent replace is reconciled by the gate on the next sweep.+ */+ private static final class StoredFileResource extends AbstractResource+ implements StoredFileBacked {++ private final StorageProvider storageProvider;+ private final Long fileId;+ private final String storageKey;+ private final String filename;+ private final long sizeBytes;++ private StoredFileResource(StorageProvider storageProvider, StoredFile file) {+ this.storageProvider = storageProvider;+ this.fileId = file.getId();+ this.storageKey = file.getStorageKey();+ this.filename = file.getOriginalFilename();+ this.sizeBytes = file.getSizeBytes();+ }++ @Override+ public Long storedFileId() {+ return fileId;+ }++ @Override+ public InputStream getInputStream() throws IOException {+ return storageProvider.load(storageKey).getInputStream();+ }++ /** Listed just now; readers get a precise error from {@link #getInputStream} instead. */+ @Override+ public boolean exists() {+ return true;+ }++ @Override+ public long contentLength() {+ return sizeBytes;+ }++ @Override+ public String getFilename() {+ return filename;+ }++ @Override+ public String getDescription() {+ return "stored file " + filename + " (" + storageKey + ")";+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StoredFileBacked.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StoredFileBacked.javanew file mode 100644index 0000000000..85c51b94c9--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StoredFileBacked.java@@ -0,0 +1,10 @@+package stirling.software.proprietary.policy.input;++/**+ * Marks an input {@link org.springframework.core.io.Resource} as backed by a row in app storage, so+ * an output sink writing back to storage (a new version of the input) can find the origin file.+ */+public interface StoredFileBacked {++ Long storedFileId();+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/InProcessProcessedLedger.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/InProcessProcessedLedger.javaindex 436e62f2c8..f851a45e0b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/InProcessProcessedLedger.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/InProcessProcessedLedger.java@@ -97,6 +97,47 @@ public class InProcessProcessedLedger implements ProcessedLedger {return true;}+ @Override+ public synchronized boolean reclaimFailed(String policyId, String identity, String gate) {+ Map<String, Row> rows = rowsByPolicy.get(policyId);+ Row row = rows == null ? null : rows.get(identity);+ if (row == null || row.status != ProcessedFileStatus.ERROR || !gate.equals(row.gate)) {+ return false;+ }+ row.status = ProcessedFileStatus.PROCESSING;+ row.attempts++;+ row.lastSeen = nowMillis.get();+ return true;+ }++ @Override+ public synchronized boolean forgetFailure(String policyId, String identity) {+ Map<String, Row> rows = rowsByPolicy.get(policyId);+ Row row = rows == null ? null : rows.get(identity);+ if (row == null || row.status != ProcessedFileStatus.ERROR) {+ return false;+ }+ rows.remove(identity);+ return true;+ }++ @Override+ public synchronized boolean forget(String policyId, String identity) {+ Map<String, Row> rows = rowsByPolicy.get(policyId);+ Row row = rows == null ? null : rows.get(identity);+ if (row == null || row.status == ProcessedFileStatus.PROCESSING) {+ return false;+ }+ rows.remove(identity);+ return true;+ }++ @Override+ public synchronized boolean anyInFlight(String policyId) {+ return rowsByPolicy.getOrDefault(policyId, Map.of()).values().stream()+ .anyMatch(row -> row.status == ProcessedFileStatus.PROCESSING);+ }+@Overridepublic synchronized void settle(String policyId,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/JpaProcessedLedger.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/JpaProcessedLedger.javaindex 02fce08763..7bc87cd0ef 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/JpaProcessedLedger.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/JpaProcessedLedger.java@@ -118,6 +118,28 @@ public class JpaProcessedLedger implements ProcessedLedger {return repository.reclaimAtNewContent(policyId, identityHash, gate, hash, now) > 0;}+ @Override+ public boolean reclaimFailed(String policyId, String identity, String gate) {+ return repository.retryErrorAtGate(+ policyId, IdentityHasher.identityHash(identity), gate, nowMillis.get())+ > 0;+ }++ @Override+ public boolean forgetFailure(String policyId, String identity) {+ return repository.deleteFailure(policyId, IdentityHasher.identityHash(identity)) > 0;+ }++ @Override+ public boolean forget(String policyId, String identity) {+ return repository.deleteSettled(policyId, IdentityHasher.identityHash(identity)) > 0;+ }++ @Override+ public boolean anyInFlight(String policyId) {+ return repository.existsByPolicyIdAndStatus(policyId, ProcessedFileStatus.PROCESSING);+ }+@Overridepublic void settle(String policyId,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedFileRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedFileRepository.javaindex def89821ae..3c32d7338f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedFileRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedFileRepository.java@@ -94,6 +94,26 @@ public interface ProcessedFileRepository@Param("maxAttempts") int maxAttempts,@Param("now") long now);+ /**+ * Retry of an ERROR row at the same gate, for a user-invoked sweep. Unbounded: unlike the+ * automatic INTERRUPTED retry, a person clicking again is the rate limiter.+ */+ @Modifying+ @Transactional+ @Query(+ "update ProcessedFileEntity e set e.status ="+ + " stirling.software.proprietary.policy.ledger.ProcessedFileStatus.PROCESSING,"+ + " e.attempts = e.attempts + 1, e.lastSeen = :now, e.updatedAt = :now"+ + " where e.policyId = :policyId and e.identityHash = :identityHash"+ + " and e.status ="+ + " stirling.software.proprietary.policy.ledger.ProcessedFileStatus.ERROR"+ + " and e.signature = :gate")+ int retryErrorAtGate(+ @Param("policyId") String policyId,+ @Param("identityHash") String identityHash,+ @Param("gate") String gate,+ @Param("now") long now);+/** Bounded retry of an INTERRUPTED row whose gate moved but whose content is unchanged. */@Modifying@Transactional@@ -139,6 +159,8 @@ public interface ProcessedFileRepositoryList<ProcessedFileEntity> findByPolicyIdAndIdentityHashIn(String policyId, Collection<String> identityHashes);+ boolean existsByPolicyIdAndStatus(String policyId, ProcessedFileStatus status);+/*** Remove an output record whose rename never landed, only while still settled exactly as* recorded; a row a claim has since taken over is left alone.@@ -155,6 +177,26 @@ public interface ProcessedFileRepository@Param("identityHash") String identityHash,@Param("gate") String gate);+ /** Per-file retry: drop a parked failure so the file is claimable as never processed. */+ @Modifying+ @Transactional+ @Query(+ "delete from ProcessedFileEntity e where e.policyId = :policyId"+ + " and e.identityHash = :identityHash and e.status ="+ + " stirling.software.proprietary.policy.ledger.ProcessedFileStatus.ERROR")+ int deleteFailure(+ @Param("policyId") String policyId, @Param("identityHash") String identityHash);++ /** Forget a settled row entirely; in-flight rows stay. */+ @Modifying+ @Transactional+ @Query(+ "delete from ProcessedFileEntity e where e.policyId = :policyId"+ + " and e.identityHash = :identityHash and e.status <>"+ + " stirling.software.proprietary.policy.ledger.ProcessedFileStatus.PROCESSING")+ int deleteSettled(+ @Param("policyId") String policyId, @Param("identityHash") String identityHash);+/** Stamp presence for the given identities; chunked by the caller for very large folders. */@Modifying@Transactionaldiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedLedger.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedLedger.javaindex 848a764f60..0beaaaa5f6 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedLedger.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/ProcessedLedger.java@@ -52,6 +52,31 @@ public interface ProcessedLedger {statesFor(policyId, List.of(identity)).get(identity));}+ /**+ * Take a parked failure back into PROCESSING at the same gate; only a user-invoked sweep calls+ * this. False when the row is no longer a same-gate failure.+ */+ boolean reclaimFailed(String policyId, String identity, String gate);++ /**+ * Forget a parked failure so the next sweep claims the file fresh. Unlike {@link+ * #reclaimFailed} the row is not put in flight, so any sweep picks it up. False when the row is+ * not currently a failure.+ */+ boolean forgetFailure(String policyId, String identity);++ /**+ * Forget a settled row so the file reads as never processed — backs revert. An in-flight row+ * stays; its run's settle would recreate it anyway. False when nothing was forgotten.+ */+ boolean forget(String policyId, String identity);++ /**+ * Whether any row is still {@link ProcessedFileStatus#PROCESSING}. A revert quiesces on this: a+ * cancelled run flips terminal at once but settles only when its task ends.+ */+ boolean anyInFlight(String policyId);+/** Record a claimed file's outcome at its final version ({@code finalContentHash} nullable). */void settle(String policyId,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/StorageFileIdentities.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/StorageFileIdentities.javanew file mode 100644index 0000000000..d9e229a0b9--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/ledger/StorageFileIdentities.java@@ -0,0 +1,45 @@+package stirling.software.proprietary.policy.ledger;++import java.io.IOException;+import java.io.InputStream;+import java.io.UncheckedIOException;+import java.security.DigestInputStream;+import java.security.MessageDigest;++import stirling.software.proprietary.billing.ContentHasher;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;++/**+ * Ledger identity and version tiers for files in app storage, shared by the storage-folder input+ * source and the storage output sink so a produced file is recorded in exactly the shape the next+ * sweep computes. Identity is the immutable row id. The cheap gate pairs {@code updatedAt} with+ * size — but metadata-only writes (a folder move, a rename) bump {@code updatedAt} too, so the gate+ * over-triggers by design and the content hash is the second tier that turns those into a gate+ * refresh instead of a reprocess.+ */+public final class StorageFileIdentities {++ private StorageFileIdentities() {}++ public static String identity(StoredFile file) {+ return "storage:" + file.getId();+ }++ public static String gate(StoredFile file) {+ return file.getUpdatedAt() + ":" + file.getSizeBytes();+ }++ /** SHA-256 of the stored blob; {@link UncheckedIOException} on read failure (propagates). */+ public static String contentHash(StorageProvider storageProvider, StoredFile file) {+ MessageDigest digest = ContentHasher.newSha256();+ try (InputStream is =+ new DigestInputStream(+ storageProvider.load(file.getStorageKey()).getInputStream(), digest)) {+ is.transferTo(java.io.OutputStream.nullOutputStream());+ return ContentHasher.toHex(digest.digest());+ } catch (IOException e) {+ throw new UncheckedIOException("could not hash stored file " + identity(file), e);+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.javaindex ce304d3109..44f20680cf 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java@@ -16,7 +16,9 @@ public record Policy(OutputSpec output,List<String> outputIds,Long teamId,- EditorConfig editor) {+ EditorConfig editor,+ /** The owning product surface; {@link #SURFACE_POLICY} unless stamped otherwise. */+ String surface) {public Policy {icon = icon == null ? "" : icon;@@ -25,8 +27,15 @@ public record Policy(output = output == null ? OutputSpec.inline() : output;outputIds = outputIds == null ? List.of() : List.copyOf(outputIds);editor = editor == null ? EditorConfig.disabled() : editor;+ surface = surface == null || surface.isBlank() ? SURFACE_POLICY : surface;}+ /** The record belongs to the org policies surface (the default). */+ public static final String SURFACE_POLICY = "policy";++ /** The record is a processing-folder pair, served only by its own route. */+ public static final String SURFACE_PROCESSING_FOLDER = "processing-folder";+/*** Without the {@code required} flag, {@code icon}, or editor participation: defaults to an* ordinary (non-blocking) pipeline, no icon, and a swept/on-demand policy. Kept for the many@@ -43,7 +52,20 @@ public record Policy(OutputSpec output,List<String> outputIds,Long teamId) {- this(id, name, owner, enabled, false, "", inputs, steps, output, outputIds, teamId, null);+ this(+ id,+ name,+ owner,+ enabled,+ false,+ "",+ inputs,+ steps,+ output,+ outputIds,+ teamId,+ null,+ SURFACE_POLICY);}/**@@ -62,7 +84,20 @@ public record Policy(List<String> outputIds,Long teamId,EditorConfig editor) {- this(id, name, owner, enabled, false, "", inputs, steps, output, outputIds, teamId, editor);+ this(+ id,+ name,+ owner,+ enabled,+ false,+ "",+ inputs,+ steps,+ output,+ outputIds,+ teamId,+ editor,+ SURFACE_POLICY);}/**@@ -124,14 +159,14 @@ public record Policy(public Policy withOutput(OutputSpec resolved) {return new Policy(id, name, owner, enabled, required, icon, inputs, steps, resolved, outputIds,- teamId, editor);+ teamId, editor, surface);}/** A copy under a different owner (e.g. moving a seed off a placeholder name). */public Policy withOwner(String newOwner) {return new Policy(id, name, newOwner, enabled, required, icon, inputs, steps, output, outputIds,- teamId, editor);+ teamId, editor, surface);}/** A copy referencing the given saved output destinations. */@@ -148,7 +183,42 @@ public record Policy(output,newOutputIds,teamId,- editor);+ editor,+ surface);+ }++ public Policy withEnabled(boolean newEnabled) {+ return new Policy(+ id,+ name,+ owner,+ newEnabled,+ required,+ icon,+ inputs,+ steps,+ output,+ outputIds,+ teamId,+ editor,+ surface);+ }++ public Policy withSurface(String newSurface) {+ return new Policy(+ id,+ name,+ owner,+ enabled,+ required,+ icon,+ inputs,+ steps,+ output,+ outputIds,+ teamId,+ editor,+ newSurface);}/**diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.javaindex 8eb0cfcc73..af912a62a0 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java@@ -47,6 +47,9 @@ public class PolicyRun {private volatile PolicyRunStatus status = PolicyRunStatus.PENDING;+ /** Set once delivery starts; a delivering run can no longer be cancelled. */+ private boolean delivering;+/** 1-based index of the step currently running (0 before the run starts). */private volatile int currentStep = 0;@@ -95,9 +98,14 @@ public class PolicyRun {return definition.steps().size();}- public synchronized void markRunning() {+ /** Marks the run running; false when already cancelled, so the task must not start. */+ public synchronized boolean markRunning() {+ if (status.isTerminal()) {+ return false;+ }this.status = PolicyRunStatus.RUNNING;touch();+ return true;}public synchronized void enterStep(int oneBasedStepIndex) {@@ -106,12 +114,18 @@ public class PolicyRun {}public synchronized void complete(List<ResultFile> resultFiles) {+ if (status == PolicyRunStatus.CANCELLED) {+ return; // cancellation is sticky: a cancelled run never reports success+ }this.outputs = resultFiles == null ? List.of() : List.copyOf(resultFiles);this.status = PolicyRunStatus.COMPLETED;touch();}public synchronized void fail(String message) {+ if (status == PolicyRunStatus.CANCELLED) {+ return; // sticky through a late failure too+ }this.error = message;this.status = PolicyRunStatus.FAILED;touch();@@ -129,14 +143,30 @@ public class PolicyRun {}public synchronized void waitForInput(WaitState wait) {+ if (status == PolicyRunStatus.CANCELLED) {+ return; // a cancelled run does not park waiting for anyone+ }this.waitState = wait;this.status = PolicyRunStatus.WAITING_FOR_INPUT;touch();}- /** Cancels unless already terminal; returns whether it transitioned. */+ /**+ * Claim the delivery phase: false when already cancelled, so the results must be discarded.+ * Once claimed, {@link #cancel()} refuses — a run writing its outputs finishes them, and a+ * revert's quiesce waits for it instead of racing the writes.+ */+ public synchronized boolean beginDelivery() {+ if (status == PolicyRunStatus.CANCELLED) {+ return false;+ }+ this.delivering = true;+ return true;+ }++ /** Cancels unless already terminal or delivering; returns whether it transitioned. */public synchronized boolean cancel() {- if (status.isTerminal()) {+ if (status.isTerminal() || delivering) {return false;}this.status = PolicyRunStatus.CANCELLED;diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.javaindex 6d98e273fc..16b7b58275 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.java@@ -21,7 +21,13 @@ public record PolicyRunView(Boolean errorSubscribed,List<ResultFile> outputs,/** When the run was created, epoch millis, so a rediscovered run shows its real age. */- long createdAt) {+ long createdAt,+ /**+ * The input document's display name, when the run's source recorded one — a client showing+ * live runs needs something to call them before any output exists. Null for uploads and+ * cross-node views, whose identity is not name-shaped.+ */+ String fileName) {public static PolicyRunView of(PolicyRun run) {return new PolicyRunView(@@ -34,7 +40,21 @@ public record PolicyRunView(run.getErrorCode(),run.getErrorSubscribed(),run.getOutputs(),- run.getCreatedAt().toEpochMilli());+ run.getCreatedAt().toEpochMilli(),+ fileNameOf(run.getFileIdentity()));+ }++ /**+ * The trailing path segment of a path-shaped file identity (a folder source's identity is the+ * document's absolute path). Identities that aren't path-shaped pass through whole — for a+ * storage source that is still a recognisable reference, and null stays null.+ */+ private static String fileNameOf(String fileIdentity) {+ if (fileIdentity == null || fileIdentity.isBlank()) {+ return null;+ }+ int cut = Math.max(fileIdentity.lastIndexOf('/'), fileIdentity.lastIndexOf('\\'));+ return cut < 0 ? fileIdentity : fileIdentity.substring(cut + 1);}/** Cross-node view from a shared job-store entry; step cursor is node-local so it reads 0. */@@ -63,6 +83,7 @@ public record PolicyRunView(null,null,outputs,- createdAt);+ createdAt,+ null);}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.javaindex c06f18a846..c5060b2b5a 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.java@@ -45,6 +45,13 @@ public class FolderOutputSink implements PolicyOutputSink {static final String TYPE = FolderAccessGuard.FOLDER_TYPE;static final String DIRECTORY_OPTION = "directory";+ /**+ * When set, an output overwrites the same-named file instead of picking a unique name.+ * Processing folders use it to process in place: the watched file becomes its result, and the+ * ledger row recorded at the result's version keeps the sweep from re-claiming it.+ */+ static final String REPLACE_OPTION = "replace";+// Staging entries are renamed away within one delivery; anything older is a crash leftover.private static final Duration STALE_TMP_AGE = Duration.ofDays(1);@@ -72,20 +79,37 @@ public class FolderOutputSink implements PolicyOutputSink {Path targetDir = accessGuard.requirePermitted(directoryOf(spec));Files.createDirectories(targetDir);Path canonicalDir = FolderIdentities.canonicalDir(targetDir);- Path tmpDir = canonicalDir.resolve(".stirling").resolve("tmp");+ Path tmpDir = stirlingDir(canonicalDir).resolve("tmp");Files.createDirectories(tmpDir);sweepStaleTmp(tmpDir);+ boolean replace = Boolean.parseBoolean(String.valueOf(spec.options().get(REPLACE_OPTION)));+ // In place means the input's name: a renaming step must not drop its result beside the+ // watched file. One-in-one-out only; a splitting pipeline lands its outputs alongside.+ String inputName =+ delivery.inputs().primary().size() == 1+ ? delivery.inputs().primary().get(0).getFilename()+ : null;+ boolean replaceInPlace = replace && outputs.size() == 1 && inputName != null;List<ResultFile> results = new ArrayList<>();for (int i = 0; i < outputs.size(); i++) {Resource resource = outputs.get(i);- String name = OutputNames.safeName(resource.getFilename(), i);+ String name =+ OutputNames.safeName(replaceInPlace ? inputName : resource.getFilename(), i);Path staged = tmpDir.resolve(UUID.randomUUID().toString());String contentHash = stage(resource, staged, delivery.policyId() != null);long size = Files.size(staged);// Size and mtime survive the rename.String gate = FolderIdentities.statGate(staged);- Path target = moveIntoPlace(delivery, canonicalDir, name, staged, gate, contentHash);+ Path target =+ moveIntoPlace(+ delivery,+ canonicalDir,+ name,+ staged,+ gate,+ contentHash,+ replaceInPlace);String contentType =MediaTypeFactory.getMediaType(name).orElse(MediaType.APPLICATION_OCTET_STREAM)@@ -135,8 +159,42 @@ public class FolderOutputSink implements PolicyOutputSink {String name,Path staged,String gate,- String contentHash)+ String contentHash,+ boolean replace)throws IOException {+ if (replace) {+ Path target = dir.resolve(name);+ // Archive before the ledger row flips DONE, so a restore that reads DONE finds the+ // original safe, never mid-move.+ Path archived = archiveOriginal(dir, target);+ try {+ if (delivery.policyId() != null) {+ processedLedger.recordOutput(+ delivery.policyId(), target.toString(), gate, contentHash);+ }+ Files.move(+ staged,+ target,+ StandardCopyOption.ATOMIC_MOVE,+ StandardCopyOption.REPLACE_EXISTING);+ } catch (IOException | RuntimeException failed) {+ if (archived != null) {+ try {+ Files.move(archived, target, StandardCopyOption.ATOMIC_MOVE);+ } catch (IOException lost) {+ log.warn(+ "Replace of {} failed and its original could not be put back: {}",+ target,+ lost.getMessage());+ }+ }+ if (delivery.policyId() != null) {+ processedLedger.forgetOutput(delivery.policyId(), target.toString(), gate);+ }+ throw failed;+ }+ return target;+ }while (true) {Path target = uniqueTarget(dir, name);if (delivery.policyId() != null) {@@ -155,6 +213,69 @@ public class FolderOutputSink implements PolicyOutputSink {}}+ /** Where a directory's pre-processing originals are kept, beside the staging dir. */+ public static Path originalsDir(Path dir) {+ return dir.resolve(".stirling").resolve("originals");+ }++ /**+ * Where a same-name re-drop's original goes once the canonical slot is taken. A subdirectory,+ * not a numbered sibling: a restore brings back every regular file directly under {@link+ * #originalsDir}, so a sibling would be restored as a file the watched folder never held.+ *+ * <p>Canonical stays with the first original, which is wrong when the user replaced the file+ * with a different document of the same name; telling that apart needs the previous output's+ * content hash, which the next claim clears from the ledger row.+ */+ private static Path supersededDir(Path dir) {+ return originalsDir(dir).resolve("superseded");+ }++ /**+ * The folder's workspace root, created hidden: a dot prefix for POSIX and the app's own+ * listings, plus the DOS attribute for Explorer where the filesystem has one.+ */+ private static Path stirlingDir(Path dir) throws IOException {+ Path root = dir.resolve(".stirling");+ Files.createDirectories(root);+ try {+ Files.setAttribute(root, "dos:hidden", true);+ } catch (UnsupportedOperationException | IOException e) {+ // Not a DOS filesystem; the dot prefix already hides it there.+ }+ return root;+ }++ /**+ * Move the target into {@code .stirling/originals} before a replace overwrites it, returning+ * the archived path, or null when nothing is at the target. Throws if an existing target cannot+ * be archived, so the caller aborts before overwriting and never destroys an unpreserved+ * original. With the canonical slot already taken, the kept original stays there and this+ * content goes to {@link #supersededDir}.+ *+ * <p>Plain move, not {@code ATOMIC_MOVE}: the archive is hidden under {@code .stirling} so+ * needs no atomic visibility, and a plain move survives a cross-device archive dir where {@code+ * ATOMIC_MOVE} would throw.+ */+ private static Path archiveOriginal(Path dir, Path target) throws IOException {+ if (!Files.exists(target)) {+ return null;+ }+ stirlingDir(dir);+ Path originals = originalsDir(dir);+ Files.createDirectories(originals);+ String name = target.getFileName().toString();+ Path archived = originals.resolve(name);+ if (Files.exists(archived)) {+ // Kept aside, so the overwrite cannot destroy this content either.+ Path superseded = supersededDir(dir);+ Files.createDirectories(superseded);+ archived = uniqueTarget(superseded, name);+ }+ Files.move(target, archived);+ return archived;+ }+/** Best-effort removal of staging leftovers from crashed deliveries. */private static void sweepStaleTmp(Path tmpDir) {Instant cutoff = Instant.now().minus(STALE_TMP_AGE);diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.javaindex ef3b59bebe..fcce40648b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java@@ -1,8 +1,22 @@package stirling.software.proprietary.policy.output;+import java.util.List;++import stirling.software.proprietary.policy.model.PolicyInputs;+/*** Context for one run's output delivery. {@code policyId} is null for ad-hoc pipelines; when* present, sinks record outputs in the processed-file ledger so the producing policy does not- * re-ingest them.+ * re-ingest them. {@code inputs} carries the run's inputs so a sink that writes back to where the+ * input lives (e.g. a new version of a stored file) can correlate output to origin.*/-public record OutputDelivery(String runId, String policyId) {}+public record OutputDelivery(String runId, String policyId, PolicyInputs inputs) {++ public OutputDelivery {+ inputs = inputs == null ? PolicyInputs.of(List.of()) : inputs;+ }++ public OutputDelivery(String runId, String policyId) {+ this(runId, policyId, null);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/StorageOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/StorageOutputSink.javanew file mode 100644index 0000000000..9c1a3b935d--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/StorageOutputSink.java@@ -0,0 +1,263 @@+package stirling.software.proprietary.policy.output;++import java.io.IOException;+import java.io.InputStream;+import java.util.ArrayList;+import java.util.List;+import java.util.UUID;++import org.springframework.core.io.Resource;+import org.springframework.http.MediaType;+import org.springframework.http.MediaTypeFactory;+import org.springframework.stereotype.Service;+import org.springframework.web.multipart.MultipartFile;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.model.job.ResultFile;+import stirling.software.proprietary.policy.input.StoredFileBacked;+import stirling.software.proprietary.policy.ledger.ProcessedLedger;+import stirling.software.proprietary.policy.ledger.StorageFileIdentities;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.model.Folder;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.storage.repository.FolderRepository;+import stirling.software.proprietary.storage.repository.StoredFileRepository;+import stirling.software.proprietary.storage.service.FileStorageService;++/**+ * Writes a run's outputs back into app storage, the output side of a processing folder. {@code+ * mode} picks: {@code new_version} (default) replaces the input file's content in place under its+ * own name, settling the ledger at the bumped version; {@code new_file} stores each output as a new+ * file in {@code folderId} (default: the input's folder), recorded in the ledger before it becomes+ * visible so a sweep never claims the policy's own output. Ownership follows the input; a run fed+ * from disk has no anchor, so it is stored as the owner of the {@code folderId} it writes into, and+ * must name one.+ */+@Slf4j+@Service+@RequiredArgsConstructor+public class StorageOutputSink implements PolicyOutputSink {++ static final String TYPE = "storage";+ static final String MODE_OPTION = "mode";+ static final String FOLDER_OPTION = "folderId";+ static final String NEW_VERSION = "new_version";+ static final String NEW_FILE = "new_file";++ private final StoredFileRepository storedFileRepository;+ private final FolderRepository folderRepository;+ private final FileStorageService fileStorageService;+ private final ProcessedLedger processedLedger;+ private final StorageProvider storageProvider;+ private final ApplicationProperties applicationProperties;++ @Override+ public String type() {+ return TYPE;+ }++ @Override+ public boolean supports(OutputSpec spec) {+ return spec != null && TYPE.equals(spec.type());+ }++ @Override+ public void validate(OutputSpec spec) {+ if (!applicationProperties.getSecurity().isEnableLogin()+ || !applicationProperties.getStorage().isEnabled()) {+ throw new IllegalArgumentException("file storage is not enabled on this server");+ }+ String mode = modeOf(spec);+ if (!NEW_VERSION.equals(mode) && !NEW_FILE.equals(mode)) {+ throw new IllegalArgumentException("unknown storage output mode: " + mode);+ }+ UUID folderId = folderIdOf(spec);+ if (folderId != null && !folderRepository.existsById(folderId)) {+ throw new IllegalArgumentException("unknown storage folder: " + folderId);+ }+ }++ @Override+ public List<ResultFile> deliver(+ OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) throws IOException {+ StoredFile origin = originOf(delivery);+ UUID folderId = folderIdOf(spec);+ User owner = ownerFor(origin, folderId);+ List<ResultFile> results = new ArrayList<>();++ // Replacing in place needs a stored row to replace, which a run fed from disk has not got.+ boolean replaceInPlace =+ origin != null && NEW_VERSION.equals(modeOf(spec)) && outputs.size() == 1;+ for (int i = 0; i < outputs.size(); i++) {+ Resource output = outputs.get(i);+ StoredFile stored;+ if (replaceInPlace) {+ // The output takes the input's place — same row, same name, new content, and+ // replaceFile keeps the row in whatever folder the user put it in.+ stored =+ fileStorageService.replaceFile(+ origin.getOwner(),+ origin,+ new ResourceMultipartFile(output, origin.getOriginalFilename()));+ } else {+ stored = storeIntoFolder(delivery, output, i, owner, origin, folderId);+ }+ results.add(+ ResultFile.builder()+ .fileId(String.valueOf(stored.getId()))+ .fileName(stored.getOriginalFilename())+ .contentType(stored.getContentType())+ .fileSize(stored.getSizeBytes())+ .build());+ log.debug(+ "Wrote policy run {} output to stored file {}",+ delivery.runId(),+ stored.getId());+ }+ return results;+ }++ /**+ * Store first (unplaced — invisible to sweeps), record the ledger row, then place into the+ * folder: the row exists before the file is discoverable.+ */+ private StoredFile storeIntoFolder(+ OutputDelivery delivery,+ Resource output,+ int index,+ User owner,+ StoredFile origin,+ UUID folderId)+ throws IOException {+ String name = OutputNames.safeName(output.getFilename(), index);+ StoredFile stored =+ fileStorageService.storeFile(owner, new ResourceMultipartFile(output, name));+ // Read the origin's placement as a plain id: it is detached here, so touching its lazy+ // folder association would fail.+ UUID targetFolder = folderId;+ if (targetFolder == null && origin != null) {+ targetFolder = storedFileRepository.findFolderIdByFileId(origin.getId()).orElse(null);+ }+ if (targetFolder == null) {+ return stored;+ }+ if (delivery.policyId() != null) {+ // The placement save below bumps updatedAt past this gate; the content hash is what+ // lets the next sweep read that bump as "already processed" rather than fresh work.+ processedLedger.recordOutput(+ delivery.policyId(),+ StorageFileIdentities.identity(stored),+ StorageFileIdentities.gate(stored),+ StorageFileIdentities.contentHash(storageProvider, stored));+ }+ stored.setFolder(folderRepository.getReferenceById(targetFolder));+ return storedFileRepository.save(stored);+ }++ /** The stored file the run's primary input came from; null when the input came from disk. */+ private StoredFile originOf(OutputDelivery delivery) {+ return delivery.inputs().primary().stream()+ .filter(StoredFileBacked.class::isInstance)+ .map(resource -> ((StoredFileBacked) resource).storedFileId())+ .flatMap(id -> storedFileRepository.findById(id).stream())+ .findFirst()+ .orElse(null);+ }++ /**+ * Who the outputs are stored as, and whose quota they count against: the input's owner, or for+ * a disk-fed run the owner of the folder being written into.+ */+ private User ownerFor(StoredFile origin, UUID folderId) {+ if (origin != null) {+ return origin.getOwner();+ }+ if (folderId == null) {+ throw new IllegalStateException(+ "storage output from a non-storage input needs a folderId to anchor ownership");+ }+ return folderRepository+ .findById(folderId)+ .map(Folder::getOwner)+ .orElseThrow(+ () -> new IllegalStateException("unknown storage folder: " + folderId));+ }++ private static String modeOf(OutputSpec spec) {+ Object mode = spec.options().get(MODE_OPTION);+ return mode == null || String.valueOf(mode).isBlank() ? NEW_VERSION : String.valueOf(mode);+ }++ private static UUID folderIdOf(OutputSpec spec) {+ Object raw = spec.options().get(FOLDER_OPTION);+ if (raw == null || String.valueOf(raw).isBlank()) {+ return null;+ }+ try {+ return UUID.fromString(String.valueOf(raw));+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException("invalid storage output folderId: " + raw, e);+ }+ }++ /** Streams a run output into the storage service's upload seam without buffering it. */+ private record ResourceMultipartFile(Resource resource, String filename)+ implements MultipartFile {++ @Override+ public String getName() {+ return "file";+ }++ @Override+ public String getOriginalFilename() {+ return filename;+ }++ @Override+ public String getContentType() {+ return MediaTypeFactory.getMediaType(filename)+ .orElse(MediaType.APPLICATION_OCTET_STREAM)+ .toString();+ }++ @Override+ public boolean isEmpty() {+ return getSize() == 0;+ }++ @Override+ public long getSize() {+ try {+ return resource.contentLength();+ } catch (IOException e) {+ return -1;+ }+ }++ @Override+ public byte[] getBytes() throws IOException {+ try (InputStream is = resource.getInputStream()) {+ return is.readAllBytes();+ }+ }++ @Override+ public InputStream getInputStream() throws IOException {+ return resource.getInputStream();+ }++ @Override+ public void transferTo(java.io.File dest) throws IOException {+ try (InputStream is = resource.getInputStream()) {+ java.nio.file.Files.copy(+ is, dest.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);+ }+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/overview/PolicyOverviewService.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/overview/PolicyOverviewService.javaindex 0ea57c4248..c9097708e7 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/overview/PolicyOverviewService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/overview/PolicyOverviewService.java@@ -22,9 +22,9 @@ import stirling.software.proprietary.policy.store.PolicyStore;/*** Builds the unified Pipelines overview: one row per policy the caller's team owns, with its* sources resolved to live display names, its steps, and a trigger/output summary. This lists EVERY- * policy - both pipelines built in the full builder and the friendly "suggested" policies - since- * the two surfaces were merged (a policy is a pipeline the org requires). No catalogue filter any- * more.+ * policy: a pipeline built in the full builder and a friendly "suggested" policy are the same+ * record underneath. Only processing folders are excluded - they share the engine but are the+ * editor's own surface.*/@Service@RequiredArgsConstructor@@ -36,6 +36,8 @@ public class PolicyOverviewService {private final SourceAccessGuard sourceAccessGuard;public PoliciesOverviewResponse overview() {+ // Processing folders are the editor's own surface (ProcessingFolderController); the+ // portal's pipelines overview never sees them.List<Policy> policies = policyAccessGuard.visibleFrom(policyStore).stream().toList();Map<String, String> sourceNames = sourceNames();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.javaindex 38d3e6ecb3..8a034b6179 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java@@ -118,6 +118,7 @@ public class DefaultClassificationPolicySeeder {List.of(),teamId,// Classification runs in the editor on every upload.- EditorConfig.onUpload());+ EditorConfig.onUpload(),+ Policy.SURFACE_POLICY);}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.javaindex 10792591d9..753c350514 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceOverviewService.java@@ -13,6 +13,7 @@ import org.springframework.stereotype.Service;import lombok.RequiredArgsConstructor;import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.controller.ProcessingFolderController;import stirling.software.proprietary.policy.model.Policy;import stirling.software.proprietary.policy.store.PolicyStore;import stirling.software.proprietary.util.SecretMasker;@@ -34,7 +35,15 @@ public class SourceOverviewService {private final SourceDocCounter docCounter;public SourcesResponse overview() {- List<Source> sources = sourceAccessGuard.visibleFrom(sourceStore);+ // Processing folders (source + policy pairs) are the editor's own surface, served by+ // ProcessingFolderController; the portal's sources/pipelines views never see them.+ List<Source> sources =+ sourceAccessGuard.visibleFrom(sourceStore).stream()+ .filter(+ source ->+ !ProcessingFolderController.SOURCE_TYPE.equals(+ source.type()))+ .toList();List<Policy> policies = policyAccessGuard.visibleFrom(policyStore);Map<String, List<Policy>> referencesBySource = referencesBySource(policies);diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.javaindex 17f872756d..1d1107aca2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/InProcessPolicyStore.java@@ -41,7 +41,8 @@ public class InProcessPolicyStore implements PolicyStore {policy.output(),policy.outputIds(),policy.teamId(),- policy.editor());+ policy.editor(),+ policy.surface());policies.put(id, stored);// Existing policy keeps its position; a new one appends to the end of its team's queue.sortOrders.computeIfAbsent(id, key -> nextSortOrder(stored.teamId()));diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.javaindex 32831d8f0f..fbf7947115 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/JpaPolicyStore.java@@ -55,7 +55,8 @@ public class JpaPolicyStore implements PolicyStore {policy.output(),policy.outputIds(),policy.teamId(),- policy.editor());+ policy.editor(),+ policy.surface());PolicyEntity entity = new PolicyEntity();entity.setId(id);@@ -156,8 +157,10 @@ public class JpaPolicyStore implements PolicyStore {private Optional<Policy> toPolicy(PolicyEntity entity) {try {JsonNode node =- liftEditorConfig(- upgradeLegacyShape(objectMapper.readTree(entity.getPolicyJson())));+ liftSurface(+ liftEditorConfig(+ upgradeLegacyShape(+ objectMapper.readTree(entity.getPolicyJson()))));// A blob written by an older version won't carry fields added since (e.g. required,// icon). Default absent primitives rather than rejecting the whole policy, so upgrades// don't drop existing pipelines.@@ -251,6 +254,24 @@ public class JpaPolicyStore implements PolicyStore {return obj;}+ /**+ * Stamp {@code surface} on a blob written before it was a first-class field, from the marker+ * processing folders used to carry in their output options. Absent both, the row is an ordinary+ * policy.+ */+ private JsonNode liftSurface(JsonNode root) {+ if (!(root instanceof ObjectNode obj) || obj.hasNonNull("surface")) {+ return root;+ }+ String marker = text(obj.path("output").path("options"), "surface");+ obj.put(+ "surface",+ Policy.SURFACE_PROCESSING_FOLDER.equals(marker)+ ? Policy.SURFACE_PROCESSING_FOLDER+ : Policy.SURFACE_POLICY);+ return obj;+ }+/** The stored moment, or the category default the client applied when none was stored. */private static String legacyRunOn(JsonNode options, String categoryId) {String stored = text(options, "runOn");diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.javaindex 5b859a4786..dc5a194cc0 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.java@@ -20,6 +20,7 @@ import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;+import org.slf4j.MDC;import org.springframework.stereotype.Service;import lombok.RequiredArgsConstructor;@@ -27,6 +28,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.policy.config.FolderAccessGuard;+import stirling.software.proprietary.policy.engine.PolicyEngine;import stirling.software.proprietary.policy.engine.PolicyRunner;import stirling.software.proprietary.policy.engine.SweepKind;import stirling.software.proprietary.policy.input.InputSource;@@ -210,7 +212,28 @@ public class FolderWatchTrigger implements PolicyTrigger {binding.policy().id(),binding.input().sourceId());// Light: the periodic reconcile does the full sweep.- policyRunner.runInput(binding.policy(), binding.input(), SweepKind.LIGHT);+ runAsOwner(binding, SweepKind.LIGHT);+ }+ }+ }++ /**+ * Run one binding as its policy's owner: watch threads have no security context, so run ids+ * would mint unscoped and stay invisible to the owner's runs feed on a login install.+ */+ private void runAsOwner(PolicyBinding binding, SweepKind sweep) {+ String owner = binding.policy().owner();+ String previous = MDC.get(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY);+ if (owner != null) {+ MDC.put(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY, owner);+ }+ try {+ policyRunner.runInput(binding.policy(), binding.input(), sweep);+ } finally {+ if (previous != null) {+ MDC.put(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY, previous);+ } else if (owner != null) {+ MDC.remove(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY);}}}@@ -228,7 +251,7 @@ public class FolderWatchTrigger implements PolicyTrigger {void runAll() {for (PolicyBinding binding : policyStore.findBindingsByTriggerType(TYPE)) {try {- policyRunner.runInput(binding.policy(), binding.input(), SweepKind.FULL);+ runAsOwner(binding, SweepKind.FULL);} catch (RuntimeException e) {log.warn("Folder-watch reconcile run failed for input {}/{}: {}",diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.javaindex f5f9301ad3..a034b5609c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java@@ -341,6 +341,7 @@ public class UserService implements UserServiceInterface {}}+ @Overridepublic boolean usernameExists(String username) {return findByUsername(username).isPresent();}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.javaindex b7ff77c987..4b52c56e42 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.java@@ -2,6 +2,7 @@ package stirling.software.proprietary.storage.repository;import java.util.List;import java.util.Optional;+import java.util.UUID;import org.springframework.data.domain.Pageable;import org.springframework.data.jpa.repository.JpaRepository;@@ -60,6 +61,15 @@ public interface StoredFileRepository extends JpaRepository<StoredFile, Long> {List<StoredFile> findAllByOwner(User owner);+ List<StoredFile> findAllByFolderId(UUID folderId);++ /**+ * A file's folder placement as a plain id. Reads the FK directly so callers outside a+ * transaction never touch the lazy {@code folder} association.+ */+ @Query("SELECT sf.folder.id FROM StoredFile sf WHERE sf.id = :fileId")+ Optional<UUID> findFolderIdByFileId(@Param("fileId") Long fileId);+/*** Bulk lookup used by the folder-placement controller. Returns only files owned by {@code* owner}; ids that don't exist or that belong to another user are silently dropped so thediff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.javaindex 7b7d9b68a6..fb5575ea28 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java@@ -49,6 +49,7 @@ import stirling.software.proprietary.storage.provider.StorageProvider;import stirling.software.proprietary.storage.provider.StoredObject;import stirling.software.proprietary.storage.repository.FileShareAccessRepository;import stirling.software.proprietary.storage.repository.FileShareRepository;+import stirling.software.proprietary.storage.repository.FolderRepository;import stirling.software.proprietary.storage.repository.StorageCleanupEntryRepository;import stirling.software.proprietary.storage.repository.StoredFileRepository;@@ -63,6 +64,7 @@ public class FileStorageService {Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$");private final StoredFileRepository storedFileRepository;+ private final FolderRepository folderRepository;private final FileShareRepository fileShareRepository;private final FileShareAccessRepository fileShareAccessRepository;private final UserRepository userRepository;@@ -218,6 +220,16 @@ public class FileStorageService {applyAuditMetadata(existing, auditObject);}+ // The entity is often detached (policy runs deliver on worker threads with no open+ // persistence context), and its lazy folder association is then an unreadable proxy+ // from a closed session — merging that drops the FK, silently moving the file to the+ // file-manager root. Re-anchor the placement as a fresh reference, read by plain id.+ existing.setFolder(+ storedFileRepository+ .findFolderIdByFileId(existing.getId())+ .map(folderRepository::getReferenceById)+ .orElse(null));+StoredFile updated;try {updated = storedFileRepository.save(existing);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.javaindex 431d74d8b8..550318447f 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@@ -29,12 +29,16 @@ import stirling.software.proprietary.policy.source.SourceStore;*/class FolderAccessGuardTest {+ private static final String TAURI_MODE_PROPERTY = "STIRLING_PDF_TAURI_MODE";+@TempDir Path tempDir;private final SourceStore sourceStore = new InProcessSourceStore();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();environment.setActiveProfiles(activeProfiles);@@ -45,6 +49,7 @@ class FolderAccessGuardTest {private FolderAccessGuard guardWithStorage(List<String> allowedRoots, boolean storageEnabled, String provider, String basePath) {ApplicationProperties properties = new ApplicationProperties();+ properties.getSecurity().setEnableLogin(true);properties.getPolicies().setAllowedFolderRoots(allowedRoots);ApplicationProperties.Storage storage = properties.getStorage();storage.setEnabled(storageEnabled);@@ -59,6 +64,7 @@ class FolderAccessGuardTest {private FolderAccessGuard guardWithWatchedFolder(String watchedDir) {ApplicationProperties properties = new ApplicationProperties();+ properties.getSecurity().setEnableLogin(true);properties.getSystem().getCustomPaths()@@ -96,6 +102,49 @@ class FolderAccessGuardTest {() -> guard.requirePermitted(tempDir.resolve("..").resolve("escaped")));}+ @Test+ void deniesAnUnlistedDirectoryOnAServerWithLoginOff() {+ // Login off does not mean "desktop": a self-hosted server runs this way by default, and+ // there every caller is unauthenticated, so the allowlist is all that stands between them+ // and the filesystem.+ assertThrows(+ FolderAccessDeniedException.class,+ () -> guardWithLoginOff().requirePermitted(tempDir));+ }++ @Test+ void permitsAnyDirectoryInTheDesktopBundle() {+ withDesktopBundle(+ () ->+ assertEquals(+ tempDir.toAbsolutePath().normalize(),+ guardWithLoginOff().requirePermitted(tempDir)));+ }++ private FolderAccessGuard guardWithLoginOff() {+ ApplicationProperties properties = new ApplicationProperties();+ return new FolderAccessGuard(+ properties,+ new RuntimePathConfig(properties),+ new StandardEnvironment(),+ sourceStore);+ }++ /** Runs the body with the flag the desktop sidecar sets, restoring whatever was there. */+ private static void withDesktopBundle(Runnable body) {+ String previous = System.getProperty(TAURI_MODE_PROPERTY);+ System.setProperty(TAURI_MODE_PROPERTY, "true");+ try {+ body.run();+ } finally {+ if (previous == null) {+ System.clearProperty(TAURI_MODE_PROPERTY);+ } else {+ System.setProperty(TAURI_MODE_PROPERTY, previous);+ }+ }+ }+@Testvoid rejectsEverythingWhenNoRootsAreConfigured() {FolderAccessGuard guard = guard(List.of());diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/PolicyAccessGuardTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/PolicyAccessGuardTest.javaindex c3f6552dc5..34a7d3e3e5 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/PolicyAccessGuardTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/PolicyAccessGuardTest.java@@ -88,6 +88,60 @@ class PolicyAccessGuardTest {assertNull(guard(false).teamForNewPolicy());}+ @Test+ void policiesSurfaceNeverSeesProcessingFolderRows() {+ when(policyManagementAuthority.currentUserTeamId()).thenReturn(1L);+ PolicyStore store = new InProcessPolicyStore();+ store.save(inTeam(1L));+ store.save(folderPair(1L, "alice"));++ assertEquals(1, guard(true).visibleFrom(store).size());+ assertEquals(1, guard(false).visibleFrom(store).size()); // login off hides them too+ }++ @Test+ void processingFoldersAreScopedToTheirOwnerNotTheirTeam() {+ when(policyManagementAuthority.currentUserTeamId()).thenReturn(1L);+ when(userService.getCurrentUsername()).thenReturn("alice");+ PolicyStore store = new InProcessPolicyStore();+ store.save(folderPair(1L, "alice"));+ store.save(folderPair(1L, "bob")); // same team, different person+ store.save(inTeam(1L)); // ordinary policy, not a folder++ List<Policy> visible = guard(true).visibleProcessingFolders(store);++ assertEquals(1, visible.size());+ assertEquals("alice", visible.get(0).owner());+ }++ @Test+ void canAccessAProcessingFolderOnlyAsItsOwner() {+ when(userService.getCurrentUsername()).thenReturn("alice");+ assertTrue(guard(true).canAccess(folderPair(1L, "alice")));+ assertFalse(guard(true).canAccess(folderPair(1L, "bob")));+ assertTrue(guard(false).canAccess(folderPair(1L, "bob"))); // local operator+ }++ @Test+ void aNullOwnerProcessingFolderIsNotReachableUnderLogin() {+ // Nobody, not every authenticated user. The null-owner short-circuit returns false+ // without reading the current user, so there is no username to stub.+ assertFalse(guard(true).canAccess(folderPair(1L, null)));+ }++ private static Policy folderPair(Long teamId, String owner) {+ return new Policy(+ null,+ "pair",+ owner,+ true,+ List.of(),+ List.of(),+ OutputSpec.inline(),+ teamId)+ .withSurface(Policy.SURFACE_PROCESSING_FOLDER);+ }+private static Policy inTeam(Long teamId) {return new Policy(null, "p", "owner", true, List.of(), List.of(), OutputSpec.inline(), teamId);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.javaindex 8d69b84fc9..e99b51e65c 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java@@ -47,6 +47,7 @@ import stirling.software.proprietary.policy.engine.PolicyRunHandle;import stirling.software.proprietary.policy.engine.PolicyRunRegistry;import stirling.software.proprietary.policy.engine.PolicyRunner;import stirling.software.proprietary.policy.engine.PolicyValidator;+import stirling.software.proprietary.policy.engine.SweepKind;import stirling.software.proprietary.policy.engine.SweepOutcome;import stirling.software.proprietary.policy.ledger.ProcessedLedger;import stirling.software.proprietary.policy.model.OutputSpec;@@ -420,7 +421,7 @@ class PolicyControllerTest {when(jobOwnershipService.createScopedJobKey("owned")).thenReturn("owned");when(jobOwnershipService.createScopedJobKey("other")).thenReturn("scoped-other");- List<PolicyRunView> views = controller.listRuns();+ List<PolicyRunView> views = controller.listRuns(null);assertThat(views).hasSize(1);assertThat(views.get(0).runId()).isEqualTo("owned");@@ -450,6 +451,23 @@ class PolicyControllerTest {verify(policyTriggerManager).notifyPoliciesChanged();}+ @Test+ @DisplayName("a client-supplied surface is overwritten server-side")+ void surfaceIsServerStamped() {+ applicationProperties.getSecurity().setEnableLogin(true);+ when(policyManagementAuthority.canEditPolicies()).thenReturn(true);+ when(policyAccessGuard.ownerForNewPolicy()).thenReturn("alice");+ when(policyAccessGuard.teamForNewPolicy()).thenReturn(7L);+ when(policyStore.save(any())).thenAnswer(i -> i.getArgument(0));++ Policy incoming = policy(null, null).withSurface("processing-folder");+ ResponseEntity<Policy> response = controller.savePolicy(incoming);++ // A forged folder-surface row would be operable through the folders API yet+ // invisible to team management.+ assertThat(response.getBody().surface()).isEqualTo(Policy.SURFACE_POLICY);+ }+@Test@DisplayName("saving the sentinel back keeps the stored output secret")void saveRestoresOutputSecrets() {@@ -512,7 +530,8 @@ class PolicyControllerTest {null,List.of(),null,- null);+ null,+ Policy.SURFACE_POLICY);assertThatThrownBy(() -> controller.savePolicy(withUnknownSource)).isInstanceOf(ResponseStatusException.class)@@ -609,6 +628,16 @@ class PolicyControllerTest {assertThat(result).hasSize(2);}+ @Test+ @DisplayName("a processing-folder row is invisible to the policies surface")+ void getRefusesAProcessingFolderRow() {+ Policy pair = policy("f", 1L).withSurface(Policy.SURFACE_PROCESSING_FOLDER);+ when(policyStore.get("f")).thenReturn(Optional.of(pair));++ // Even its owner cannot reach it here; only the folder route serves it.+ assertThat(controller.getPolicy("f").getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);+ }+@Test@DisplayName("getPolicy returns the policy when accessible")void getAccessible() {@@ -915,8 +944,8 @@ class PolicyControllerTest {Policy p = policy("a", 1L);when(policyStore.get("a")).thenReturn(Optional.of(p));when(policyAccessGuard.canAccess(p)).thenReturn(true);- SweepOutcome outcome = new SweepOutcome(List.of("run-a", "run-b"), 3, 1, 0, 0);- when(policyRunner.run(p)).thenReturn(outcome);+ SweepOutcome outcome = new SweepOutcome(List.of("run-a", "run-b"), 3, 1, 0, 0, 0);+ when(policyRunner.run(p, SweepKind.USER)).thenReturn(outcome);ResponseEntity<SweepOutcome> response = controller.trigger("a");@@ -964,8 +993,8 @@ class PolicyControllerTest {Policy p = policy("a", 1L);when(policyStore.get("a")).thenReturn(Optional.of(p));when(policyAccessGuard.canAccess(p)).thenReturn(true);- SweepOutcome outcome = new SweepOutcome(List.of("run-a"), 1, 0, 0, 0);- when(policyRunner.run(p)).thenReturn(outcome);+ SweepOutcome outcome = new SweepOutcome(List.of("run-a"), 1, 0, 0, 0, 0);+ when(policyRunner.run(p, SweepKind.USER)).thenReturn(outcome);ResponseEntity<SweepOutcome> response = controller.trigger("a");@@ -983,8 +1012,8 @@ class PolicyControllerTest {Policy p = policy("a", null);when(policyStore.get("a")).thenReturn(Optional.of(p));when(policyAccessGuard.canAccess(p)).thenReturn(true);- SweepOutcome outcome = new SweepOutcome(List.of("run-a"), 1, 0, 0, 0);- when(policyRunner.run(p)).thenReturn(outcome);+ SweepOutcome outcome = new SweepOutcome(List.of("run-a"), 1, 0, 0, 0, 0);+ when(policyRunner.run(p, SweepKind.USER)).thenReturn(outcome);assertThat(controller.trigger("a").getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);verify(policyManagementAuthority, never()).canTriggerPolicies();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.javanew file mode 100644index 0000000000..31958469e1--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java@@ -0,0 +1,655 @@+package stirling.software.proprietary.policy.controller;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.timeout;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.nio.file.Files;+import java.nio.file.Path;+import java.time.LocalDateTime;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;+import java.util.stream.Stream;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.api.io.TempDir;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.web.server.ResponseStatusException;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.UserServiceInterface;+import stirling.software.proprietary.policy.config.FolderAccessGuard;+import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.engine.PolicyRunner;+import stirling.software.proprietary.policy.engine.PolicyValidator;+import stirling.software.proprietary.policy.engine.SweepKind;+import stirling.software.proprietary.policy.engine.SweepOutcome;+import stirling.software.proprietary.policy.input.InputSource;+import stirling.software.proprietary.policy.input.StorageFolderInputSource;+import stirling.software.proprietary.policy.ledger.ClaimState;+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.output.PolicyOutputSink;+import stirling.software.proprietary.policy.output.StorageOutputSink;+import stirling.software.proprietary.policy.source.InProcessSourceStore;+import stirling.software.proprietary.policy.store.InProcessPolicyStore;+import stirling.software.proprietary.policy.trigger.PolicyTrigger;+import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.model.Folder;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.storage.repository.FolderRepository;+import stirling.software.proprietary.storage.repository.StoredFileRepository;+import stirling.software.proprietary.storage.service.FileStorageService;++/**+ * Tests for {@link ProcessingFolderController}: the source + policy pair composes and tears down+ * together, an invalid pipeline rolls the pair back, only the caller's own folders qualify, and the+ * records stay invisible to the policies surface.+ */+@ExtendWith(MockitoExtension.class)+class ProcessingFolderControllerTest {++ private static final UUID FOLDER_ID = UUID.randomUUID();++ @TempDir Path tempDir;++ @Mock private PolicyRunner policyRunner;+ @Mock private PolicyTriggerManager policyTriggerManager;+ @Mock private ProcessedLedger processedLedger;+ @Mock private FolderRepository folderRepository;+ @Mock private FileStorageService fileStorageService;+ @Mock private StoredFileRepository storedFileRepository;+ @Mock private StorageProvider storageProvider;+ @Mock private UserServiceInterface userService;+ @Mock private PolicyManagementAuthority policyManagementAuthority;+ @Mock private FolderAccessGuard folderAccessGuard;+ @Mock private PolicyTrigger folderWatchTrigger;+ @Mock private InputSource diskFolderSource;+ @Mock private stirling.software.proprietary.policy.asset.PolicyAssetStore assetStore;+ @Mock private stirling.software.common.service.ToolChainValidator toolChainValidator;+ @Mock private PolicyOutputSink diskFolderSink;++ private final InProcessPolicyStore policyStore = new InProcessPolicyStore();+ private final InProcessSourceStore sourceStore = new InProcessSourceStore();++ private User user;+ private Folder folder;+ private ProcessingFolderController controller;++ @BeforeEach+ void setUp() {+ ApplicationProperties properties = new ApplicationProperties();+ properties.getSecurity().setEnableLogin(true);+ properties.getStorage().setEnabled(true);++ user = new User();+ user.setId(7L);+ user.setUsername("reece");+ folder = new Folder();+ folder.setId(FOLDER_ID);+ folder.setName("Contracts");+ folder.setOwner(user);++ lenient().when(fileStorageService.requireAuthenticatedUser()).thenReturn(user);+ // A disk-backed folder creates a storage folder to deliver its results into, then looks it+ // up again on the next save. The double has to remember what it stored for that second+ // lookup to find anything — otherwise every save mints a fresh folder.+ Map<UUID, Folder> folders = new HashMap<>();+ folders.put(FOLDER_ID, folder);+ lenient()+ .when(folderRepository.saveAndFlush(any(Folder.class)))+ .thenAnswer(+ invocation -> {+ Folder saved = invocation.getArgument(0);+ folders.put(saved.getId(), saved);+ return saved;+ });+ lenient()+ .when(folderRepository.findById(any(UUID.class)))+ .thenAnswer(+ invocation -> Optional.ofNullable(folders.get(invocation.getArgument(0))));+ lenient()+ .when(folderRepository.existsById(any(UUID.class)))+ .thenAnswer(invocation -> folders.containsKey(invocation.getArgument(0)));+ lenient().when(userService.getCurrentUsername()).thenReturn("reece");+ lenient().when(policyManagementAuthority.currentUserTeamId()).thenReturn(3L);+ lenient()+ .when(policyRunner.run(any(), any()))+ .thenReturn(new SweepOutcome(List.of("run-1"), 1, 0, 0, 0, 0));+ // Nothing runs in these tests, so per-file revert's quiet check passes.+ lenient().when(policyRunner.quiesced(any())).thenReturn(true);++ PolicyAccessGuard accessGuard =+ new PolicyAccessGuard(userService, properties, policyManagementAuthority);+ // The real FolderWatchTrigger is a bean; without one registered the validator reads+ // "folder-watch" as an unknown trigger type.+ lenient().when(folderWatchTrigger.type()).thenReturn("folder-watch");+ // Likewise the disk folder source and sink: real beans in the app, stubbed here so a+ // disk-backed folder validates without touching the filesystem.+ lenient().when(diskFolderSource.supports(any())).thenReturn(true);+ lenient().when(diskFolderSink.supports(any())).thenReturn(true);+ PolicyValidator validator =+ new PolicyValidator(+ List.of(folderWatchTrigger),+ List.of(+ new StorageFolderInputSource(+ storedFileRepository,+ folderRepository,+ storageProvider,+ properties),+ diskFolderSource),+ List.of(+ new StorageOutputSink(+ storedFileRepository,+ folderRepository,+ fileStorageService,+ processedLedger,+ storageProvider,+ properties),+ diskFolderSink),+ List.of(),+ sourceStore,+ assetStore,+ toolChainValidator);+ controller =+ new ProcessingFolderController(+ policyStore,+ sourceStore,+ validator,+ policyRunner,+ policyTriggerManager,+ processedLedger,+ folderRepository,+ storedFileRepository,+ fileStorageService,+ accessGuard,+ folderAccessGuard,+ properties);+ }++ @Test+ void createComposesAValidatedPairAndSweepsTheBacklog() {+ var view = controller.save(request(null, "new_version")).getBody();++ assertThat(view.folderId()).isEqualTo(FOLDER_ID.toString());+ assertThat(view.enabled()).isTrue();+ Policy stored = policyStore.get(view.id()).orElseThrow();+ assertThat(ProcessingFolderController.isProcessingFolder(stored)).isTrue();+ assertThat(stored.owner()).isEqualTo("reece");+ assertThat(stored.teamId()).isEqualTo(3L);+ assertThat(stored.inputs()).hasSize(1);+ var source = sourceStore.get(stored.inputs().get(0).sourceId()).orElseThrow();+ assertThat(source.type()).isEqualTo("storage-folder");+ assertThat(source.options()).containsEntry("folderId", FOLDER_ID.toString());+ verify(policyRunner, timeout(2000)).run(stored, SweepKind.USER);+ }++ @Test+ void aForeignOutputFolderIdIsOverriddenWithTheOwnedSourceFolder() {+ // The caller owns FOLDER_ID but points output at someone else's folder.+ String foreign = "00000000-0000-0000-0000-0000000000ff";+ var view =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ FOLDER_ID.toString(),+ null,+ true,+ List.of(+ new PipelineStep(+ "/api/v1/misc/flatten",+ Map.of("flattenOnlyForms", false),+ Map.of())),+ Map.of("mode", "new_file", "folderId", foreign)))+ .getBody();++ Policy stored = policyStore.get(view.id()).orElseThrow();+ assertThat(stored.output().options())+ .containsEntry("folderId", FOLDER_ID.toString())+ .doesNotContainValue(foreign);+ }++ @Test+ void aCreateOverAnExistingPlaceAdoptsItWithoutReconfiguring() {+ var first = controller.save(request(null, "new_version")).getBody();+ Policy before = policyStore.get(first.id()).orElseThrow();++ var second =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ FOLDER_ID.toString(),+ null,+ false,+ List.of(),+ Map.of()))+ .getBody();++ // Same record, untouched configuration.+ assertThat(second.id()).isEqualTo(first.id());+ Policy after = policyStore.get(first.id()).orElseThrow();+ assertThat(after.steps()).isEqualTo(before.steps());+ assertThat(after.enabled()).isEqualTo(before.enabled());+ verify(policyRunner, timeout(2000).times(2)).run(any(), any());+ }++ @Test+ void aDiskFolderIsWatchedSoArrivalsProcessThemselves() {+ var view =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ null,+ "/tmp/Downloads",+ true,+ List.of(+ new PipelineStep(+ "/api/v1/misc/flatten",+ Map.of("flattenOnlyForms", false),+ Map.of())),+ Map.of()))+ .getBody();++ Policy stored = policyStore.get(view.id()).orElseThrow();+ // Without a trigger the engine treats the policy as manual-only: the creating sweep would+ // run and the directory would never be processed again.+ assertThat(stored.inputs()).hasSize(1);+ assertThat(stored.inputs().get(0).trigger()).isNotNull();+ assertThat(stored.inputs().get(0).trigger().type()).isEqualTo("folder-watch");+ var source = sourceStore.get(stored.inputs().get(0).sourceId()).orElseThrow();+ assertThat(source.type()).isEqualTo("folder");+ // Never "consume": the directory is the user's own and must stay intact.+ assertThat(source.options()).containsEntry("mode", "track");+ assertThat(source.options()).containsEntry("limit", 100);+ }++ @Test+ void aDiskFolderProcessesInPlace() {+ var view =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ null,+ "/tmp/Downloads",+ true,+ List.of(+ new PipelineStep(+ "/api/v1/misc/flatten",+ Map.of("flattenOnlyForms", false),+ Map.of())),+ Map.of()))+ .getBody();++ Policy stored = policyStore.get(view.id()).orElseThrow();+ // Disk, not app storage: an install with no accounts and no file storage has nothing to+ // store a result against. Results replace the watched files in place.+ assertThat(stored.output().type()).isEqualTo("folder");+ assertThat(stored.output().options().get("directory")).isEqualTo("/tmp/Downloads");+ assertThat(stored.output().options().get("replace")).isEqualTo(true);+ }++ @Test+ void aDiskFolderReportsTheDirectoryItWatchesNotWhereResultsGo() {+ var view =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ null,+ "/tmp/Downloads",+ true,+ List.of(+ new PipelineStep(+ "/api/v1/misc/flatten",+ Map.of("flattenOnlyForms", false),+ Map.of())),+ Map.of()))+ .getBody();++ // The client shows this as the folder's address, so it has to be the watched directory —+ // reading it off the output made the folder advertise its own results subdirectory.+ assertThat(view.directory()).isEqualTo("/tmp/Downloads");+ assertThat(view.folderId()).isNull();+ }++ @Test+ void aStorageFolderStaysManualUntilTheArrivalTriggerExists() {+ var view = controller.save(request(null, "new_version")).getBody();++ assertThat(policyStore.get(view.id()).orElseThrow().inputs().get(0).trigger()).isNull();+ }++ @Test+ void anInvalidPipelineRollsBackTheSource() {+ assertThatThrownBy(() -> controller.save(request(null, "no_such_mode")))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("mode");++ assertThat(sourceStore.all()).isEmpty();+ assertThat(policyStore.all()).isEmpty();+ }++ @Test+ void anotherUsersFolderReadsAsNotFound() {+ User stranger = new User();+ stranger.setId(8L);+ folder.setOwner(stranger);++ assertThatThrownBy(() -> controller.save(request(null, "new_version")))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("No folder");+ assertThat(sourceStore.all()).isEmpty();+ }++ @Test+ void deleteTearsDownThePairAndItsHistory() {+ var view = controller.save(request(null, "new_version")).getBody();++ controller.delete(view.id());++ assertThat(policyStore.all()).isEmpty();+ assertThat(sourceStore.all()).isEmpty();+ verify(processedLedger).clearPolicy(view.id());+ }++ @Test+ void listShowsOnlyProcessingFolders() {+ controller.save(request(null, "new_version"));+ // An org policy in the same team is not a processing folder and stays invisible here.+ policyStore.save(+ new Policy(+ null,+ "Security Policy",+ "reece",+ true,+ List.of(),+ List.of(),+ stirling.software.proprietary.policy.model.OutputSpec.inline(),+ List.of(),+ 3L,+ null));++ assertThat(controller.list()).hasSize(1);+ }++ @Test+ void aStorageFolderListsItsFilesWithTheirLedgerState() {+ var view = controller.save(request(null, "new_version")).getBody();+ StoredFile done = storedFile(11L, "done.pdf");+ StoredFile waiting = storedFile(12L, "waiting.pdf");+ when(storedFileRepository.findAllByFolderId(FOLDER_ID)).thenReturn(List.of(done, waiting));+ when(processedLedger.statesFor(eq(view.id()), any()))+ .thenReturn(+ Map.of("storage:11", new ClaimState(ProcessedFileStatus.DONE, "g", null)));++ var files = controller.files(view.id());++ assertThat(files).hasSize(2);+ assertThat(files.get(0).name()).isEqualTo("done.pdf");+ assertThat(files.get(0).state()).isEqualTo("done");+ assertThat(files.get(1).state()).isEqualTo("waiting");+ }++ @Test+ void retryRunsOnlyTheNamedFile() {+ var view = controller.save(request(null, "new_version")).getBody();+ StoredFile doc = storedFile(11L, "doc.pdf");+ when(storedFileRepository.findAllByFolderId(FOLDER_ID)).thenReturn(List.of(doc));+ when(processedLedger.forgetFailure(view.id(), "storage:11")).thenReturn(true);++ controller.retryFile(view.id(), new ProcessingFolderController.RetryFileRequest("doc.pdf"));++ Policy stored = policyStore.get(view.id()).orElseThrow();+ // Scoped to the one file: a whole-folder sweep would also claim every file with no+ // ledger row, including an original a restore just brought back.+ verify(policyRunner).runFile(stored, "storage:11");+ }++ @Test+ void retryRefusesAFileWithNoParkedFailure() {+ var view = controller.save(request(null, "new_version")).getBody();+ StoredFile doc = storedFile(11L, "doc.pdf");+ when(storedFileRepository.findAllByFolderId(FOLDER_ID)).thenReturn(List.of(doc));+ when(processedLedger.forgetFailure(view.id(), "storage:11")).thenReturn(false);++ assertThatThrownBy(+ () ->+ controller.retryFile(+ view.id(),+ new ProcessingFolderController.RetryFileRequest("doc.pdf")))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("no failure");+ }++ @Test+ void revertRestoresPausesAndForgetsSoTheFileReadsUnprocessed() throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();+ Files.writeString(tempDir.resolve("doc.pdf"), "processed");+ Path originals = tempDir.resolve(".stirling").resolve("originals");+ Files.createDirectories(originals);+ Files.writeString(originals.resolve("doc.pdf"), "original");++ var restored =+ controller.revertFile(+ view.id(), new ProcessingFolderController.RevertFileRequest("doc.pdf"));++ assertThat(Files.readString(tempDir.resolve("doc.pdf"))).isEqualTo("original");+ assertThat(Files.exists(originals.resolve("doc.pdf"))).isFalse();+ assertThat(restored.state()).isEqualTo("waiting");+ // Forgotten, not settled: the file reads as unprocessed until the folder resumes.+ verify(processedLedger).forget(eq(view.id()), anyString());+ assertThat(policyStore.get(view.id()).orElseThrow().enabled()).isFalse();+ }++ @Test+ void revertRefusesAFileWithNoArchivedOriginal() throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();+ Files.writeString(tempDir.resolve("doc.pdf"), "processed");++ assertThatThrownBy(+ () ->+ controller.revertFile(+ view.id(),+ new ProcessingFolderController.RevertFileRequest(+ "doc.pdf")))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("no original");+ }++ @Test+ void revertAllRestoresEveryArchivedOriginal() throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();+ Path originals = tempDir.resolve(".stirling").resolve("originals");+ Files.createDirectories(originals);+ for (String name : List.of("doc1.pdf", "doc2.pdf")) {+ Files.writeString(tempDir.resolve(name), "processed");+ Files.writeString(originals.resolve(name), "original");+ }++ var outcome = controller.revertAllFiles(view.id());++ assertThat(outcome.restored()).isEqualTo(2);+ assertThat(outcome.skipped()).isZero();+ assertThat(Files.readString(tempDir.resolve("doc1.pdf"))).isEqualTo("original");+ assertThat(Files.readString(tempDir.resolve("doc2.pdf"))).isEqualTo("original");+ assertThat(Files.exists(originals.resolve("doc1.pdf"))).isFalse();+ assertThat(policyStore.get(view.id()).orElseThrow().enabled()).isFalse();+ verify(policyRunner).cancelRuns(view.id());+ verify(policyRunner).awaitQuiesce(eq(view.id()), any());+ // Failed rows go too: the reset leaves every file reading as waiting.+ verify(processedLedger).clearPolicy(view.id());+ }++ @Test+ void revertAllIgnoresNestedArchivesSoItRestoresOnlyTheFolderSOwnFiles() throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();+ Path originals = tempDir.resolve(".stirling").resolve("originals");+ // The consumer half of the superseded layout: a same-name re-drop displaces the original+ // it replaces one level down, and revert-all must leave it there. Restoring it as a+ // sibling would leave the user a second "doc.pdf" their folder never held. The write half+ // - that only the canonical name ever lands in this namespace - is pinned by+ // FolderOutputSinkTest.aSupersededOriginalIsKeptOutOfTheRestoreNamespace.+ Path superseded = originals.resolve("superseded");+ Files.createDirectories(superseded);+ Files.writeString(tempDir.resolve("doc.pdf"), "processed");+ Files.writeString(originals.resolve("doc.pdf"), "the-original");+ Files.writeString(superseded.resolve("doc.pdf"), "displaced-original");++ var outcome = controller.revertAllFiles(view.id());++ assertThat(outcome.restored()).isEqualTo(1);+ assertThat(Files.readString(tempDir.resolve("doc.pdf"))).isEqualTo("the-original");+ try (Stream<Path> entries = Files.list(tempDir)) {+ assertThat(entries.filter(Files::isRegularFile).map(f -> f.getFileName().toString()))+ .containsExactly("doc.pdf");+ }+ // Still preserved, just not restored over anything.+ assertThat(Files.readString(superseded.resolve("doc.pdf"))).isEqualTo("displaced-original");+ }++ @Test+ void revertAllWithNothingArchivedStillResetsTheFolder() throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();++ var outcome = controller.revertAllFiles(view.id());++ assertThat(outcome.restored()).isZero();+ assertThat(outcome.skipped()).isZero();+ // No files moved, but the reset still lands: paused, cancelled, history gone.+ assertThat(policyStore.get(view.id()).orElseThrow().enabled()).isFalse();+ verify(policyRunner).cancelRuns(view.id());+ verify(policyRunner).awaitQuiesce(eq(view.id()), any());+ verify(processedLedger).clearPolicy(view.id());+ }++ @Test+ void resumingAPausedFolderSweepsImmediately() {+ var view = controller.save(request(null, "new_version")).getBody();+ // Pause: no sweep. Resume: sweeps like creation, so waiting files catch up now+ // rather than at the next reconcile tick.+ controller.save(pausedCopy(view, false));+ controller.save(pausedCopy(view, true));++ // Both sweeps run behind their responses; the runs feed carries the progress.+ verify(policyRunner, timeout(2000).times(2)).run(any(Policy.class), eq(SweepKind.USER));+ }++ /** The stored record re-saved with only its enabled flag changed. */+ private ProcessingFolderController.SaveProcessingFolderRequest pausedCopy(+ ProcessingFolderController.ProcessingFolderView view, boolean enabled) {+ return new ProcessingFolderController.SaveProcessingFolderRequest(+ view.id(), view.folderId(), null, enabled, view.steps(), view.output());+ }++ @Test+ void aPausedCreateStillSweepsItsBacklog() {+ var view =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ null,+ "/tmp/Downloads",+ false,+ List.of(+ new PipelineStep(+ "/api/v1/misc/flatten",+ Map.of("flattenOnlyForms", false),+ Map.of())),+ Map.of()))+ .getBody();++ Policy stored = policyStore.get(view.id()).orElseThrow();+ assertThat(stored.enabled()).isFalse();+ // The pause lives on the policy alone: a disabled source is skipped by every sweep,+ // which would silently no-op the born-paused Downloads trick's own backlog sweep.+ var source = sourceStore.get(stored.inputs().get(0).sourceId()).orElseThrow();+ assertThat(source.enabled()).isTrue();+ verify(policyRunner, timeout(2000)).run(stored, SweepKind.USER);+ }++ /** A disk-backed folder over the test's own temp directory. */+ private ProcessingFolderController.SaveProcessingFolderRequest diskRequest() {+ return new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ null,+ tempDir.toString(),+ true,+ List.of(+ new PipelineStep(+ "/api/v1/misc/flatten",+ Map.of("flattenOnlyForms", false),+ Map.of())),+ Map.of());+ }++ @Test+ void cancelStopsTheFoldersRuns() {+ var view = controller.save(request(null, "new_version")).getBody();+ when(policyRunner.cancelRuns(view.id())).thenReturn(3);++ assertThat(controller.cancelRuns(view.id()).cancelled()).isEqualTo(3);+ }++ /** A stored file double with just what the listing reads. */+ private static StoredFile storedFile(long id, String name) {+ StoredFile file = mock(StoredFile.class);+ lenient().when(file.getId()).thenReturn(id);+ lenient().when(file.getOriginalFilename()).thenReturn(name);+ lenient().when(file.getSizeBytes()).thenReturn(100L);+ lenient().when(file.getUpdatedAt()).thenReturn(LocalDateTime.of(2026, 1, 1, 0, 0));+ return file;+ }++ private static ProcessingFolderController.SaveProcessingFolderRequest request(+ String id, String mode) {+ return new ProcessingFolderController.SaveProcessingFolderRequest(+ id,+ FOLDER_ID.toString(),+ null,+ true,+ List.of(+ new PipelineStep(+ "/api/v1/misc/flatten",+ Map.of("flattenOnlyForms", false),+ Map.of())),+ Map.of("mode", mode));+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.javaindex 1efe094fe4..ac1683935e 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java@@ -639,8 +639,8 @@ class PolicyEngineTest {"test never released the tool call");return ResponseEntity.ok(pdf("rotated", "rotated.pdf"));});- when(fileStorage.storeInputStream(any(InputStream.class), anyString()))- .thenReturn(new StoredFile("file-1", 7L));+ // No storage stub on purpose: a cancelled run must not deliver, so nothing may+ // reach file storage - if delivery regresses, the missing stub fails this loudly.PolicyRunHandle handle =engine.submit(diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.javaindex ebcf316c25..98c3b6f73f 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java@@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyLong;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.times;@@ -29,10 +30,13 @@ import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.core.io.ByteArrayResource;+import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.UserServiceInterface;+import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;import stirling.software.proprietary.policy.input.InputSource;import stirling.software.proprietary.policy.input.ResolveContext;import stirling.software.proprietary.policy.input.ResolvedInput;-import stirling.software.proprietary.policy.ledger.IdentityHasher;import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;import stirling.software.proprietary.policy.ledger.ProcessedLedger;import stirling.software.proprietary.policy.model.InputSpec;@@ -73,19 +77,21 @@ class PolicyRunnerTest {List.of(folderSource),sourceStore,docCounter,- processedLedger);+ processedLedger,+ new ApplicationProperties(),+ reachableOwners());}@Testvoid runsOnceWithNoFilesWhenThePolicyHasNoSources() {Policy policy = policy(List.of());- when(policyEngine.runPolicy(eq(policy), any(), any(), any(), any()))+ when(policyEngine.runPolicy(eq(policy), any(), any(), any(), any(), any())).thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));runner.run(policy);ArgumentCaptor<PolicyInputs> inputs = ArgumentCaptor.forClass(PolicyInputs.class);- verify(policyEngine).runPolicy(eq(policy), inputs.capture(), any(), any(), any());+ verify(policyEngine).runPolicy(eq(policy), inputs.capture(), any(), any(), any(), any());assertTrue(inputs.getValue().primary().isEmpty());// Ledger hygiene still runs: rows recorded for a generator policy's folder outputs// are pruned by its own sweeps rather than accumulating until the policy is deleted.@@ -101,7 +107,9 @@ class PolicyRunnerTest {List.of(folderSource),sourceStore,new InProcessSourceDocCounter(),- ledger);+ ledger,+ new ApplicationProperties(),+ reachableOwners());InputSpec spec = InputSpec.folder("/in");Policy policy = policy(List.of(spec));// One file already processed at its current version, one parked by a failed run.@@ -138,12 +146,12 @@ class PolicyRunnerTest {List.of(ResolvedInput.of(PolicyInputs.of(List.of())),ResolvedInput.of(PolicyInputs.of(List.of()))));- when(policyEngine.runPolicy(any(), any(), any(), any(), any()))+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any())).thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));runner.run(policy);- verify(policyEngine, times(2)).runPolicy(eq(policy), any(), any(), any(), any());+ verify(policyEngine, times(2)).runPolicy(eq(policy), any(), any(), any(), any(), any());}@Test@@ -155,7 +163,7 @@ class PolicyRunnerTest {when(folderSource.supports(spec)).thenReturn(true);when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(unit));CompletableFuture<PolicyRun> completion = new CompletableFuture<>();- when(policyEngine.runPolicy(any(), any(), any(), any(), any()))+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any())).thenReturn(new PolicyRunHandle("r", completion));runner.run(policy);@@ -176,7 +184,7 @@ class PolicyRunnerTest {when(folderSource.supports(spec)).thenReturn(true);when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(unit));CompletableFuture<PolicyRun> completion = new CompletableFuture<>();- when(policyEngine.runPolicy(any(), any(), any(), any(), any()))+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any())).thenReturn(new PolicyRunHandle("r", completion));runner.run(policy);@@ -225,12 +233,12 @@ class PolicyRunnerTest {when(folderSource.supports(spec)).thenReturn(true);when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(ResolvedInput.of(PolicyInputs.of(List.of()))));- when(policyEngine.runPolicy(any(), any(), any(), any(), any()))+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any())).thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));runner.run(policy, SweepKind.LIGHT);- verify(policyEngine).runPolicy(eq(policy), any(), any(), any(), any());+ verify(policyEngine).runPolicy(eq(policy), any(), any(), any(), any(), any());verify(processedLedger, never()).markSeen(any(), any());verify(processedLedger, never()).deleteUnseen(any(), anyLong());}@@ -245,13 +253,14 @@ class PolicyRunnerTest {when(folderSource.resolve(eq(broken), any())).thenThrow(new IOException("mount gone"));when(folderSource.resolve(eq(healthy), any())).thenReturn(List.of(ResolvedInput.of(PolicyInputs.of(List.of()))));- when(policyEngine.runPolicy(any(), any(), any(), any(), any()))+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any())).thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));runner.run(policy);verify(policyEngine)- .runPolicy(eq(policy), any(), any(), any(), any()); // healthy source still ran+ .runPolicy(+ eq(policy), any(), any(), any(), any(), any()); // healthy source still ranverify(processedLedger, never()).deleteUnseen(any(), anyLong()); // history preserved}@@ -318,9 +327,9 @@ class PolicyRunnerTest {}@Test- void anUnattendedRunStillCarriesItsSourcesHashedIdentity() throws Exception {- // The other id space, unchanged: a folder identity is a path, and a path is a filename, so- // what reaches the run is the one-way hash and never the client-minted kind of reference.+ void anUnattendedRunCarriesItsSourcesIdentityByName() throws Exception {+ // The identity reaches the run as the source produced it - name-shaped, so the run can+ // be displayed by the file it processes and a released claim resolves in the ledger.InputSpec spec = InputSpec.folder("/in");Policy policy = policy(List.of(spec));String sourceId = policy.inputs().getFirst().sourceId();@@ -330,18 +339,13 @@ class PolicyRunnerTest {List.of(ResolvedInput.forFile(PolicyInputs.of(List.of()), "/in/doc.pdf", success -> {})));- when(policyEngine.runPolicy(any(), any(), any(), any(), any()))+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any())).thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));runner.run(policy);verify(policyEngine)- .runPolicy(- eq(policy),- any(),- any(),- eq(sourceId),- eq(IdentityHasher.identityHash("/in/doc.pdf")));+ .runPolicy(eq(policy), any(), any(), eq(sourceId), eq("/in/doc.pdf"), any());}@Test@@ -371,6 +375,59 @@ class PolicyRunnerTest {assertEquals(2, docCounter.statsFor(List.of(key)).get(key).total());}+ @Test+ void anOwnerlessProcessingFolderIsNotSweptUnderLogin() {+ // Created while login was disabled, so stamped with no owner; enabling login strands it+ // where no user can list, pause, revert, or delete it. Sweeping it anyway would keep+ // replacing files in place in a folder nobody can reach.+ assertNotSwept(policy(List.of()).withOwner(null));+ }++ @Test+ void aProcessingFolderWhoseOwnerNoLongerExistsIsNotSwept() {+ // Renaming or deleting the owner strands the folder the same way a null owner does: the+ // stamped name matches no user, so the owner check fails for everyone.+ assertNotSwept(policy(List.of()).withOwner("renamed-away"));+ }++ /** Asserts the engine refuses this processing folder under login, and starts no run. */+ private void assertNotSwept(Policy stranded) {+ ApplicationProperties loginOn = new ApplicationProperties();+ loginOn.getSecurity().setEnableLogin(true);+ PolicyRunner enforced =+ new PolicyRunner(+ policyEngine,+ List.of(folderSource),+ sourceStore,+ docCounter,+ processedLedger,+ loginOn,+ guardOver(loginOn, noUsers()));++ SweepOutcome outcome = enforced.run(stranded.withSurface(Policy.SURFACE_PROCESSING_FOLDER));++ assertTrue(outcome.runIds().isEmpty());+ verifyNoInteractions(policyEngine);+ }++ /** A guard with login off, so it reports no orphans and never reads a user. */+ private static PolicyAccessGuard reachableOwners() {+ return guardOver(new ApplicationProperties(), mock(UserServiceInterface.class));+ }++ /** A user service with an empty users table: every stamped owner reads as gone. */+ private static UserServiceInterface noUsers() {+ UserServiceInterface users = mock(UserServiceInterface.class);+ // lenient: a null owner is stranded without the guard ever reaching the lookup.+ lenient().when(users.usernameExists(any())).thenReturn(false);+ return users;+ }++ private static PolicyAccessGuard guardOver(+ ApplicationProperties properties, UserServiceInterface users) {+ return new PolicyAccessGuard(users, properties, mock(PolicyManagementAuthority.class));+ }+/** Persists each spec as a source and returns a policy referencing them by id. */private Policy policy(List<InputSpec> sources) {List<String> sourceIds =@@ -396,4 +453,43 @@ class PolicyRunnerTest {private static Source disabledSourceFrom(InputSpec spec) {return new Source(null, "src", spec.type(), spec.options(), false, "owner", null);}++ @Test+ void awaitQuiesceReturnsOnceRunsSettle() {+ when(policyEngine.hasActiveRuns("p1")).thenReturn(true, false);++ assertTrue(runner.awaitQuiesce("p1", java.time.Duration.ofSeconds(2)));+ }++ @Test+ void awaitQuiesceTimesOutOnARunThatNeverSettles() {+ when(policyEngine.hasActiveRuns("p1")).thenReturn(true);++ assertFalse(runner.awaitQuiesce("p1", java.time.Duration.ofMillis(50)));+ }++ @Test+ void aQueueFullRejectionReleasesTheClaimForTheNextSweep() throws Exception {+ InputSpec spec = InputSpec.folder("/in");+ Policy policy = policy(List.of(spec));+ java.util.concurrent.atomic.AtomicBoolean outcome =+ new java.util.concurrent.atomic.AtomicBoolean(true);+ ResolvedInput unit =+ new ResolvedInput(PolicyInputs.of(List.of()), "/in/doc.pdf", outcome::set);+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(unit));+ CompletableFuture<PolicyRun> completion = new CompletableFuture<>();+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any()))+ .thenReturn(new PolicyRunHandle("r", completion));+ runner.run(policy);++ PolicyRun run = mock(PolicyRun.class);+ when(run.getStatus()).thenReturn(PolicyRunStatus.FAILED);+ when(run.getErrorCode()).thenReturn("POLICY_QUEUE_FULL");+ completion.complete(run);++ // Nothing was attempted on the file: the claim is dropped, not parked failed.+ assertFalse(outcome.get());+ verify(processedLedger).forget("p1", "/in/doc.pdf");+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicySweepTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicySweepTest.javanew file mode 100644index 0000000000..769faec4cf--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicySweepTest.java@@ -0,0 +1,33 @@+package stirling.software.proprietary.policy.engine;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import org.junit.jupiter.api.Test;++import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;++/** The claim gate, which is where a sweep's scope is decided. */+class PolicySweepTest {++ @Test+ void aTargetedSweepClaimsThatIdentityAndRefusesEveryOther() {+ PolicySweep sweep =+ new PolicySweep(+ "p1", SweepKind.LIGHT, new InProcessProcessedLedger(), "/in/wanted.pdf");++ assertTrue(sweep.claim("/in/wanted.pdf", "gate-1", () -> null));+ // Refused even though it has no ledger row: a per-file retry must not pick up the+ // folder's other unclaimed files, such as an original a restore just brought back.+ assertFalse(sweep.claim("/in/restored.pdf", "gate-2", () -> null));+ }++ @Test+ void anUntargetedSweepClaimsAnything() {+ PolicySweep sweep =+ new PolicySweep("p1", SweepKind.LIGHT, new InProcessProcessedLedger(), null);++ assertTrue(sweep.claim("/in/a.pdf", "gate-1", () -> null));+ assertTrue(sweep.claim("/in/b.pdf", "gate-2", () -> null));+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.javaindex bcb968ca8d..94e1bd52ab 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java@@ -55,6 +55,9 @@ class FolderInputSourceTest {@BeforeEachvoid setUp() {ApplicationProperties properties = new ApplicationProperties();+ // With login off the guard permits the local operator everywhere; these tests+ // exercise the allowlist, so they opt into login like a hosted install.+ properties.getSecurity().setEnableLogin(true);properties.getPolicies().setAllowedFolderRoots(List.of(tempDir.toString()));FolderAccessGuard guard =new FolderAccessGuard(@@ -397,4 +400,41 @@ class FolderInputSourceTest {present.addAll(identities);}}++ @Test+ void aCappedSweepTakesTheNewestFiles() throws IOException {+ Path inputDir = Files.createDirectories(tempDir.resolve("in"));+ Instant base = Instant.now().minusSeconds(600);+ for (int i = 0; i < 4; i++) {+ Path file = inputDir.resolve("doc" + i + ".pdf");+ Files.writeString(file, "data-" + i);+ Files.setLastModifiedTime(file, FileTime.from(base.plusSeconds(i * 60L)));+ }+ InputSpec spec =+ new InputSpec(+ "folder",+ Map.of("directory", inputDir.toString(), "mode", "track", "limit", 2));++ List<ResolvedInput> work = source.resolve(spec, ctx);++ // The cap goes to the most recently added files, not whichever listed first.+ assertEquals(2, work.size());+ assertEquals(+ List.of("doc3.pdf", "doc2.pdf"),+ work.stream().map(unit -> unit.inputs().primary().get(0).getFilename()).toList());+ }++ @Test+ void aUnitsIdentityIsTheDocumentsPathSoRunsCanNameIt() throws IOException {+ Path inputDir = Files.createDirectories(tempDir.resolve("in"));+ Files.writeString(inputDir.resolve("doc.pdf"), "data");+ InputSpec spec =+ new InputSpec("folder", Map.of("directory", inputDir.toString(), "mode", "track"));++ List<ResolvedInput> work = source.resolve(spec, ctx);++ // Name-shaped end to end: the run's display name and the ledger's claim release+ // both resolve this identity as the source produced it.+ assertTrue(work.get(0).fileIdentity().endsWith("doc.pdf"));+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderInputSourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderInputSourceTest.javanew file mode 100644index 0000000000..0bad1d732e--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderInputSourceTest.java@@ -0,0 +1,233 @@+package stirling.software.proprietary.policy.input;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.time.LocalDateTime;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;+import java.util.function.Supplier;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.core.io.ByteArrayResource;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;+import stirling.software.proprietary.policy.model.InputSpec;+import stirling.software.proprietary.storage.model.FilePurpose;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.storage.repository.FolderRepository;+import stirling.software.proprietary.storage.repository.StoredFileRepository;++/**+ * Tests for {@link StorageFolderInputSource}: files are claimed once per content version, an+ * in-place output settles at its own post-run version instead of re-triggering, a genuine edit is+ * picked up again, and purpose-bound files are never ingested.+ */+@ExtendWith(MockitoExtension.class)+class StorageFolderInputSourceTest {++ private static final String POLICY = "p1";+ private static final UUID FOLDER = UUID.randomUUID();+ private static final LocalDateTime T1 = LocalDateTime.of(2026, 7, 1, 10, 0);+ private static final LocalDateTime T2 = LocalDateTime.of(2026, 7, 1, 10, 5);++ @Mock private StoredFileRepository storedFileRepository;+ @Mock private FolderRepository folderRepository;+ @Mock private StorageProvider storageProvider;++ private StorageFolderInputSource source;+ private InProcessProcessedLedger ledger;+ private RecordingContext ctx;+ // Stands in for the blob store: hashing reads whatever this currently holds.+ private byte[] blobContent = "content-v1".getBytes();++ @BeforeEach+ void setUp() throws IOException {+ lenient()+ .when(storageProvider.load(anyString()))+ .thenAnswer(invocation -> new ByteArrayResource(blobContent));+ source =+ new StorageFolderInputSource(+ storedFileRepository,+ folderRepository,+ storageProvider,+ storageEnabledProperties());+ ledger = new InProcessProcessedLedger();+ ctx = new RecordingContext();+ }++ @Test+ void claimsEachFileOncePerContentVersion() throws IOException {+ StoredFile file = storedFile(1L, "doc.pdf", T1);+ when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));+ when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));++ List<ResolvedInput> work = source.resolve(spec(), ctx);++ assertEquals(1, work.size());+ assertEquals("doc.pdf", work.get(0).inputs().primary().get(0).getFilename());+ // In flight: a second sweep does not pick it up again.+ assertTrue(source.resolve(spec(), ctx).isEmpty());++ // Settled at an unchanged version: still nothing new to do.+ work.get(0).onComplete().accept(true);+ assertTrue(source.resolve(spec(), ctx).isEmpty());+ }++ @Test+ void anInPlaceOutputDoesNotRetriggerTheFolder() throws IOException {+ StoredFile file = storedFile(1L, "doc.pdf", T1);+ when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));++ List<ResolvedInput> work = source.resolve(spec(), ctx);++ // The run replaces the file's content in place before completion fires.+ file.setUpdatedAt(T2);+ when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));+ work.get(0).onComplete().accept(true);++ // The next sweep sees the bumped version already settled — no self-feeding loop.+ assertTrue(source.resolve(spec(), ctx).isEmpty());+ }++ @Test+ void aGenuineEditIsPickedUpAgain() throws IOException {+ StoredFile file = storedFile(1L, "doc.pdf", T1);+ when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));+ when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));++ source.resolve(spec(), ctx).get(0).onComplete().accept(true);++ // The user re-uploads: gate and content both change — fresh work.+ file.setUpdatedAt(T2);+ blobContent = "content-v2".getBytes();+ assertEquals(1, source.resolve(spec(), ctx).size());+ }++ @Test+ void aMetadataOnlyBumpDoesNotReprocess() throws IOException {+ StoredFile file = storedFile(1L, "doc.pdf", T1);+ when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));+ when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));++ source.resolve(spec(), ctx).get(0).onComplete().accept(true);++ // A folder move / rename bumps updatedAt but not the content: the hash tier refreshes the+ // gate instead of reprocessing.+ file.setUpdatedAt(T2);+ assertTrue(source.resolve(spec(), ctx).isEmpty());+ }++ @Test+ void purposeBoundFilesAreNeverIngested() throws IOException {+ StoredFile signing = storedFile(2L, "contract.pdf", T1);+ signing.setPurpose(FilePurpose.SIGNING_ORIGINAL);+ when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(signing));++ assertTrue(source.resolve(spec(), ctx).isEmpty());+ assertTrue(ctx.present.isEmpty());+ }++ @Test+ void aFailedRunLeavesTheFileForItsNextVersion() throws IOException {+ StoredFile file = storedFile(1L, "doc.pdf", T1);+ when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));+ when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));++ source.resolve(spec(), ctx).get(0).onComplete().accept(false);++ // Failed at this version: not retried until the content changes.+ assertTrue(source.resolve(spec(), ctx).isEmpty());+ file.setUpdatedAt(T2);+ blobContent = "content-v2".getBytes();+ assertEquals(1, source.resolve(spec(), ctx).size());+ }++ @Test+ void validateRejectsAnUnknownFolder() {+ when(folderRepository.existsById(FOLDER)).thenReturn(false);++ assertThrows(IllegalArgumentException.class, () -> source.validate(spec()));+ }++ @Test+ void validateRejectsAMissingFolderId() {+ assertThrows(+ IllegalArgumentException.class,+ () -> source.validate(new InputSpec("storage-folder", Map.of())));+ }++ @Test+ void validateRejectsWhenStorageIsDisabled() {+ StorageFolderInputSource disabled =+ new StorageFolderInputSource(+ storedFileRepository,+ folderRepository,+ storageProvider,+ new ApplicationProperties());++ assertThrows(IllegalArgumentException.class, () -> disabled.validate(spec()));+ }++ private static InputSpec spec() {+ return new InputSpec("storage-folder", Map.of("folderId", FOLDER.toString()));+ }++ private static StoredFile storedFile(Long id, String name, LocalDateTime updatedAt) {+ StoredFile file = new StoredFile();+ file.setId(id);+ file.setOriginalFilename(name);+ file.setStorageKey("key-" + id);+ file.setSizeBytes(100);+ file.setUpdatedAt(updatedAt);+ return file;+ }++ private static ApplicationProperties storageEnabledProperties() {+ ApplicationProperties properties = new ApplicationProperties();+ properties.getSecurity().setEnableLogin(true);+ properties.getStorage().setEnabled(true);+ return properties;+ }++ private class RecordingContext implements ResolveContext {++ private final List<String> present = new ArrayList<>();++ @Override+ public boolean claim(String identity, String gate, Supplier<String> contentHash) {+ return ledger.claim(POLICY, identity, gate, contentHash);+ }++ @Override+ public void settle(+ String identity, String finalGate, String finalContentHash, boolean success) {+ ledger.settle(POLICY, identity, finalGate, finalContentHash, success);+ }++ @Override+ public boolean allSettledDone(String identity) {+ return ledger.allSettledDone(identity);+ }++ @Override+ public void reportPresent(Collection<String> identities) {+ present.addAll(identities);+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/ledger/ProcessedLedgerContractTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/ledger/ProcessedLedgerContractTest.javaindex 800e8a6bde..413476fffe 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/ledger/ProcessedLedgerContractTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/ledger/ProcessedLedgerContractTest.java@@ -42,6 +42,38 @@ abstract class ProcessedLedgerContractTest {assertFalse(ledger.claim(POLICY, FILE, NEW_GATE, null)); // new version waits for settle}+ @Test+ void aForgottenFailureIsClaimableAsNewWork() {+ assertTrue(ledger.claim(POLICY, FILE, GATE, null));+ ledger.settle(POLICY, FILE, GATE, null, false);+ assertTrue(ledger.forgetFailure(POLICY, FILE));+ assertTrue(ledger.claim(POLICY, FILE, GATE, null)); // same gate; no row parks it+ }++ @Test+ void onlyAParkedFailureCanBeForgotten() {+ assertFalse(ledger.forgetFailure(POLICY, FILE)); // no row+ assertTrue(ledger.claim(POLICY, FILE, GATE, null));+ assertFalse(ledger.forgetFailure(POLICY, FILE)); // in flight+ ledger.settle(POLICY, FILE, GATE, null, true);+ assertFalse(ledger.forgetFailure(POLICY, FILE)); // done is history worth keeping+ }++ @Test+ void aForgottenRowReadsAsNeverProcessed() {+ assertTrue(ledger.claim(POLICY, FILE, GATE, null));+ ledger.settle(POLICY, FILE, GATE, null, true);+ assertTrue(ledger.forget(POLICY, FILE));+ assertTrue(ledger.claim(POLICY, FILE, GATE, null)); // same gate: no row parks it+ }++ @Test+ void anInFlightRowCannotBeForgotten() {+ assertTrue(ledger.claim(POLICY, FILE, GATE, null));+ assertFalse(ledger.forget(POLICY, FILE));+ assertFalse(ledger.forget(POLICY, "missing"));+ }+@Testvoid aSettledFileIsSkippedAtTheSameGate() {ledger.claim(POLICY, FILE, GATE, null);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.javanew file mode 100644index 0000000000..2db5871964--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java@@ -0,0 +1,48 @@+package stirling.software.proprietary.policy.model;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.List;++import org.junit.jupiter.api.Test;++/**+ * Cancellation is sticky: a cancelled run can neither restart nor report an outcome, so a revert+ * that cancelled it can trust the run to stay cancelled.+ */+class PolicyRunTest {++ private static PolicyRun run() {+ return new PolicyRun(+ "run-1", "p1", new PipelineDefinition("t", List.of(), List.of()), null, null, null);+ }++ @Test+ void aCancelledRunCannotStart() {+ PolicyRun run = run();+ assertTrue(run.cancel());+ assertFalse(run.markRunning());+ assertEquals(PolicyRunStatus.CANCELLED, run.getStatus());+ }++ @Test+ void aCancelledRunKeepsItsStatusThroughCompleteAndFail() {+ PolicyRun run = run();+ assertTrue(run.markRunning());+ assertTrue(run.cancel());+ run.complete(List.of());+ assertEquals(PolicyRunStatus.CANCELLED, run.getStatus());+ run.fail("late failure");+ assertEquals(PolicyRunStatus.CANCELLED, run.getStatus());+ }++ @Test+ void anOrdinaryRunStillCompletes() {+ PolicyRun run = run();+ assertTrue(run.markRunning());+ run.complete(List.of());+ assertEquals(PolicyRunStatus.COMPLETED, run.getStatus());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.javaindex 7f9acf4fae..cd9bc89649 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.java@@ -26,6 +26,7 @@ import stirling.software.proprietary.policy.config.FolderAccessGuard;import stirling.software.proprietary.policy.ledger.FolderIdentities;import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.PolicyInputs;import stirling.software.proprietary.policy.source.InProcessSourceStore;/**@@ -45,6 +46,9 @@ class FolderOutputSinkTest {@BeforeEachvoid setUp() {ApplicationProperties properties = new ApplicationProperties();+ // With login off the guard permits the local operator everywhere; these tests+ // exercise the allowlist, so they opt into login like a hosted install.+ properties.getSecurity().setEnableLogin(true);properties.getPolicies().setAllowedFolderRoots(List.of(tempDir.toString()));ledger = new InProcessProcessedLedger();sink =@@ -113,6 +117,7 @@ class FolderOutputSinkTest {Path out = tempDir.resolve("out");VisibilityAssertingLedger orderedLedger = new VisibilityAssertingLedger();ApplicationProperties properties = new ApplicationProperties();+ properties.getSecurity().setEnableLogin(true);properties.getPolicies().setAllowedFolderRoots(List.of(tempDir.toString()));FolderOutputSink orderedSink =new FolderOutputSink(@@ -184,6 +189,159 @@ class FolderOutputSinkTest {assertFalse(Files.exists(tempDir.resolve("escape.pdf")));}+ @Test+ void replaceKeepsTheFirstOriginalForRevert() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out);+ Files.writeString(out.resolve("a.pdf"), "original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace);+ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v2")), replace);++ assertEquals("v2", Files.readString(out.resolve("a.pdf")));+ // The archive holds what the user put in, not any intermediate result.+ Path archived = out.resolve(".stirling").resolve("originals").resolve("a.pdf");+ assertEquals("original", Files.readString(archived));+ }++ @Test+ void archiveFailureAbortsTheReplaceInsteadOfDestroyingTheOriginal() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out.resolve(".stirling"));+ Files.writeString(out.resolve("a.pdf"), "original");+ // Block the originals dir by occupying its path with a regular file, so archiving throws+ // exactly as an unwritable/locked/full originals dir would in the field.+ Files.writeString(out.resolve(".stirling").resolve("originals"), "blocker");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ assertThrows(+ IOException.class,+ () -> sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace));++ assertEquals("original", Files.readString(out.resolve("a.pdf")));+ }++ @Test+ void aReDroppedSameNameFileKeepsItsOwnOriginalRatherThanLosingIt() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out);+ Files.writeString(out.resolve("a.pdf"), "first-original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed1")), replace);+ // The user drops a genuinely different document under the same name; it is reprocessed.+ Files.writeString(out.resolve("a.pdf"), "second-original");+ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed2")), replace);++ assertEquals("processed2", Files.readString(out.resolve("a.pdf")));+ Path originals = out.resolve(".stirling").resolve("originals");+ assertEquals("first-original", Files.readString(originals.resolve("a.pdf")));+ // The second original was preserved, not overwritten away.+ boolean kept;+ try (Stream<Path> archived = Files.walk(originals)) {+ kept =+ archived.filter(Files::isRegularFile)+ .anyMatch(+ p -> {+ try {+ return "second-original".equals(Files.readString(p));+ } catch (IOException e) {+ return false;+ }+ });+ }+ assertTrue(kept, "the re-dropped original must be preserved, never silently lost");+ }++ @Test+ void aSupersededOriginalIsKeptOutOfTheRestoreNamespace() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out);+ Files.writeString(out.resolve("a.pdf"), "first-original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed1")), replace);+ Files.writeString(out.resolve("a.pdf"), "second-original");+ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed2")), replace);++ // A restore brings back every regular file directly under originals/, so only the+ // canonical original may sit there; a sibling would be restored as a file the folder+ // never held. The superseded one is kept, one level down.+ Path originals = out.resolve(".stirling").resolve("originals");+ List<String> restorable;+ try (Stream<Path> entries = Files.list(originals)) {+ restorable =+ entries.filter(Files::isRegularFile)+ .map(entry -> entry.getFileName().toString())+ .toList();+ }+ assertEquals(List.of("a.pdf"), restorable);+ assertEquals(+ "second-original",+ Files.readString(originals.resolve("superseded").resolve("a.pdf")));+ }++ @Test+ void aBrandNewNameArchivesNothing() throws IOException {+ Path out = tempDir.resolve("out");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace);++ assertFalse(Files.exists(out.resolve(".stirling").resolve("originals").resolve("a.pdf")));+ }++ @Test+ void replaceDeliversUnderTheInputsNameWhenAStepRenames() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out);+ Files.writeString(out.resolve("doc.pdf"), "original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(+ inPlaceRun("doc.pdf"),+ List.of(named("doc_redacted_watermarked.pdf", "v1")),+ replace);++ // The watched file became its processed self; nothing landed beside it.+ assertEquals("v1", Files.readString(out.resolve("doc.pdf")));+ assertFalse(Files.exists(out.resolve("doc_redacted_watermarked.pdf")));+ assertEquals(+ "original",+ Files.readString(out.resolve(".stirling").resolve("originals").resolve("doc.pdf")));+ }++ @Test+ void aSplittingRunDoesNotReplaceItsInput() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out);+ Files.writeString(out.resolve("doc.pdf"), "original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(+ inPlaceRun("doc.pdf"),+ List.of(named("part1.pdf", "a"), named("part2.pdf", "b")),+ replace);++ assertEquals("original", Files.readString(out.resolve("doc.pdf")));+ assertTrue(Files.exists(out.resolve("part1.pdf")));+ assertTrue(Files.exists(out.resolve("part2.pdf")));+ }++ /** A recorded run carrying its input, the shape the engine always delivers with. */+ private static OutputDelivery inPlaceRun(String inputName) {+ return new OutputDelivery(+ "run-1", "p1", PolicyInputs.of(List.of(named(inputName, "input"))));+ }+private static ByteArrayResource named(String filename, String content) {return new ByteArrayResource(content.getBytes()) {@Overridediff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.javaindex 08f38a1950..65d9577325 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/overview/PolicyOverviewServiceTest.java@@ -158,7 +158,8 @@ class PolicyOverviewServiceTest {OutputSpec.inline(),List.of(),null,- EditorConfig.disabled()));+ EditorConfig.disabled(),+ null));PolicyView view = find(service.overview(), "Mandatory redaction");assertTrue(view.required());@@ -180,7 +181,8 @@ class PolicyOverviewServiceTest {OutputSpec.inline(),List.of(),null,- EditorConfig.disabled()));+ EditorConfig.disabled(),+ null));// No explicit icon: a template-derived policy falls back to its categoryId marker.policyStore.save(new Policy(@@ -195,7 +197,8 @@ class PolicyOverviewServiceTest {new OutputSpec("inline", Map.of("categoryId", "security")),List.of(),null,- EditorConfig.disabled()));+ EditorConfig.disabled(),+ null));assertEquals("shield", find(service.overview(), "Custom with icon").icon());assertEquals("security", find(service.overview(), "Template derived").icon());diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/store/JpaPolicyStoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/store/JpaPolicyStoreTest.javaindex ae95b3a3ce..eb4abc6696 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/store/JpaPolicyStoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/store/JpaPolicyStoreTest.java@@ -72,6 +72,35 @@ class JpaPolicyStoreTest {assertEquals(saved, objectMapper.readValue(entity.getPolicyJson(), Policy.class));}+ @Test+ void aLegacyBlobLiftsItsSurfaceFromTheOutputMarker() {+ Policy pair =+ new Policy(+ "pf1",+ "Processing folder: Downloads",+ "alice",+ true,+ List.of(),+ List.of(),+ new OutputSpec("folder", Map.of("surface", "processing-folder")));+ Policy plain = new Policy("p1", "rotate", "alice", true, List.of(), List.of(), null);+ when(repository.findById("pf1")).thenReturn(Optional.of(legacyEntityFor(pair)));+ when(repository.findById("p1")).thenReturn(Optional.of(legacyEntityFor(plain)));++ assertEquals(Policy.SURFACE_PROCESSING_FOLDER, store.get("pf1").orElseThrow().surface());+ assertEquals(Policy.SURFACE_POLICY, store.get("p1").orElseThrow().surface());+ }++ /** The row as a pre-surface-field build wrote it: no {@code surface} in the JSON. */+ private PolicyEntity legacyEntityFor(Policy policy) {+ var node = (tools.jackson.databind.node.ObjectNode) objectMapper.valueToTree(policy);+ node.remove("surface");+ PolicyEntity entity = new PolicyEntity();+ entity.setId(policy.id());+ entity.setPolicyJson(node.toString());+ return entity;+ }+@Testvoid getDeserializesThePolicyFromJson() {Policy policy =diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.javaindex d254d559ee..b7b486b7d9 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.java@@ -41,6 +41,7 @@ import stirling.software.proprietary.storage.model.StoredFile;import stirling.software.proprietary.storage.provider.StorageProvider;import stirling.software.proprietary.storage.repository.FileShareAccessRepository;import stirling.software.proprietary.storage.repository.FileShareRepository;+import stirling.software.proprietary.storage.repository.FolderRepository;import stirling.software.proprietary.storage.repository.StorageCleanupEntryRepository;import stirling.software.proprietary.storage.repository.StoredFileRepository;import stirling.software.proprietary.workflow.model.WorkflowSession;@@ -52,6 +53,7 @@ import stirling.software.proprietary.workflow.model.WorkflowSession;class FileStorageServiceMoreTest {@Mock private StoredFileRepository storedFileRepository;+ @Mock private FolderRepository folderRepository;@Mock private FileShareRepository fileShareRepository;@Mock private FileShareAccessRepository fileShareAccessRepository;@Mock private UserRepository userRepository;@@ -71,6 +73,7 @@ class FileStorageServiceMoreTest {service =new FileStorageService(storedFileRepository,+ folderRepository,fileShareRepository,fileShareAccessRepository,userRepository,diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceTest.javaindex d02b04ae2b..8bac9334b0 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceTest.java@@ -35,6 +35,7 @@ import stirling.software.proprietary.storage.provider.StorageProvider;import stirling.software.proprietary.storage.provider.StoredObject;import stirling.software.proprietary.storage.repository.FileShareAccessRepository;import stirling.software.proprietary.storage.repository.FileShareRepository;+import stirling.software.proprietary.storage.repository.FolderRepository;import stirling.software.proprietary.storage.repository.StorageCleanupEntryRepository;import stirling.software.proprietary.storage.repository.StoredFileRepository;import stirling.software.proprietary.workflow.model.WorkflowSession;@@ -44,6 +45,7 @@ import stirling.software.proprietary.workflow.model.WorkflowSession;class FileStorageServiceTest {@Mock private StoredFileRepository storedFileRepository;+ @Mock private FolderRepository folderRepository;@Mock private FileShareRepository fileShareRepository;@Mock private FileShareAccessRepository fileShareAccessRepository;@Mock private UserRepository userRepository;@@ -64,6 +66,7 @@ class FileStorageServiceTest {service =new FileStorageService(storedFileRepository,+ folderRepository,fileShareRepository,fileShareAccessRepository,userRepository,diff --git a/frontend/editor/public/locales/en-GB/translation.toml b/frontend/editor/public/locales/en-GB/translation.tomlindex d2b2aa38e3..17f3df42fa 100644--- a/frontend/editor/public/locales/en-GB/translation.toml+++ b/frontend/editor/public/locales/en-GB/translation.toml@@ -4028,6 +4028,7 @@ openVersionInWorkspace = "Open in workspace"originFilter = "Filter by source"refresh = "Refresh from server"remove = "Delete"+removeLocalFolder = "Unmount from Stirling"removeVersion = "Remove this version"rename = "Rename"renamed = "Renamed"@@ -4047,6 +4048,9 @@ signInRequired = "Sign in to use cloud storage."summary_one = "{{count}} item"summary_other = "{{count}} items"tree = "Folders"+unmount = "Unmount"+unmountFolderBody = "Unmount \"{{name}}\"? The folder and its files stay on your disk."+unmountFolderTitle = "Unmount from Stirling?"upload = "Upload"uploadedToLocal = "Uploaded files start in Local. Use 'Save to cloud' to put them in a folder."uploadFromMobile = "Upload from Mobile"@@ -4079,9 +4083,20 @@ deviceHint = "Removes the local copy. The cloud copy is kept."everywhere = "Everywhere"everywhereHint = "Deletes the file from this device and the cloud."+[filesPage.diskState]+all = "All"+done = "Ready"+doneHint = "Processed — opens the result"+failed = "Failed"+processing = "Processing"+processingHint = "Processing — available when it finishes"+retry = "Retry"+retryHint = "Run this file again"+waiting = "Queued"+[filesPage.empty]hint = "Drop PDFs anywhere on this page to upload, or use the New folder button to organise your files."-newFolderCta = "Create folder"+newFolderCta = "New folder"title = "This folder is empty"uploadCta = "Upload files"@@ -4128,6 +4143,12 @@ moveFolderFailed = "Could not move folder."moveFolderFailedDetail = "Could not move folder: {{message}}"removeFilesFailed = "Could not remove files."removeFilesFailedDetail = "Could not remove files: {{message}}"+retryFailed = "Could not retry {{name}}."+retryFailedDetail = "Could not retry {{name}}: {{message}}"+revertAllFailed = "Could not restore originals."+revertAllFailedDetail = "Could not restore originals: {{message}}"+revertFailed = "Could not restore {{name}}."+revertFailedDetail = "Could not restore {{name}}: {{message}}"uploadFilesFailed = "Could not upload files."uploadFilesFailedDetail = "Could not upload files: {{message}}"@@ -4175,6 +4196,32 @@ localHint = "Only stored in this browser"shared = "Shared"sharedHint = "Shared with you via link"+[filesPage.processing]+active = "Processing folder"+edit = "Edit processing…"+nothingToRestore = "No originals to restore — these files are already their originals."+paused = "Processing paused"+remove = "Remove processing"+restore = "Restore original"+restoreAll = "Restore all originals"+resume = "Resume processing"+revertCancel = "Cancel"+revertConfirm = "Restore and pause"+revertConfirmAll = "Restore every original in this folder? Processing will be paused, and restored files show as queued until you resume."+revertConfirmFile = "Restore \"{{name}}\" to its original? Processing for this folder will be paused, and the file shows as queued until you resume."+revertConfirmTitle = "Restore originals?"+section = "Processing"+start = "Process files in this folder…"+stop = "Pause processing"+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"label = "Filter files by name"@@ -8409,6 +8456,7 @@ status = "Status"back = "Back"cancel = "Cancel"continue = "Continue"+customiseUnavailable = "The full builder lives on Processor"enablePolicy = "Enable policy"saveChanges = "Save changes"@@ -9089,6 +9137,39 @@ unlimited = "{{used}} · Unlimited"[printFile]title = "Print File"+[processingFolders.downloads]+approve = "Process my Downloads"+cancelSweep = "Cancel"+capped = "You have {{found}} PDFs; the first {{limit}} are processed now and the rest follow."+close = "Done"+explain_one = "Stirling can classify the {{count}} PDF already in your Downloads folder and open the results here."+explain_other = "Stirling can classify the {{count}} PDFs already in your Downloads folder and open the results here."+failed = "Could not set that up. Your files have not been changed."+finished_one = "Classified {{count}} file and opened {{opened}} of them here, ready to work on."+finished_other = "Classified {{count}} files and opened {{opened}} of them here, ready to work on."+keepsOriginals = "Files are processed in place — and each original is kept, so you can restore it any time."+nothingNew_one = "Nothing new to process — this {{count}} file has already been through."+nothingNew_other = "Nothing new to process — these {{count}} files have already been through."+notNow = "Not now"+progressCounts = "of {{total}} processed"+someFailed_one = "{{count}} could not be processed and was left untouched."+someFailed_other = "{{count}} could not be processed and were left untouched."+stillParked_one = "{{count}} file failed earlier and was not retried — fix the cause, then run again."+stillParked_other = "{{count}} files failed earlier and were not retried — fix the cause, then run again."+stillRunning = "Some files are still being processed in the background."+title = "Organise your Downloads?"+trigger_one = "Process {{count}} PDF in Downloads"+trigger_other = "Process {{count}} PDFs in Downloads"+typesFound_one = "{{count}} document type found"+typesFound_other = "{{count}} document types found"+working = "Processing …"++[processingFolders.wall]+done = "Done"+failed = "Failed"+title = "Processing this folder"+waiting = "Queued …"+[provider.googledrive]name = "Google Drive"scope = "File Import"@@ -11554,7 +11635,7 @@ changeFolder = "Change"chooseFolder = "Choose"clearFolder = "Clear"color = "Accent colour"-createFolder = "Create Folder"+createFolder = "New folder"createTitle = "New Watched Folder"editTitle = "Edit Watched Folder"inputFolder = "Input folder"diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex cf5369723f..cdcc26ad39 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -4388,7 +4388,7 @@ openVersionInWorkspace = "Open in workspace"originFilter = "Filter by source"refresh = "Refresh from server"remove = "Delete"-removeLocalFolder = "Remove (files stay on disk)"+removeLocalFolder = "Unmount from Stirling"removeVersion = "Remove this version"rename = "Rename"renamed = "Renamed"@@ -4409,6 +4409,9 @@ signInRequired = "Sign in to use cloud storage."summary_one = "{{count}} item"summary_other = "{{count}} items"tree = "Folders"+unmount = "Unmount"+unmountFolderBody = "Unmount \"{{name}}\"? The folder and its files stay on your disk."+unmountFolderTitle = "Unmount from Stirling?"upload = "Upload"uploadFromMobile = "Upload from Mobile"versionActions = "Version actions"@@ -4440,6 +4443,17 @@ deviceHint = "Removes the local copy. The cloud copy is kept."everywhere = "Everywhere"everywhereHint = "Deletes the file from this device and the cloud."+[filesPage.diskState]+all = "All"+done = "Ready"+doneHint = "Processed - opens the result"+failed = "Failed"+processing = "Processing"+processingHint = "Processing - available when it finishes"+retry = "Retry"+retryHint = "Run this file again"+waiting = "Queued"+[filesPage.empty]hint = "Drop PDFs anywhere on this page to upload, or use the New folder button to organize your files."title = "This folder is empty"@@ -4492,6 +4506,12 @@ removeFilesFailed = "Could not remove files."removeFilesFailedDetail = "Could not remove files: {{message}}"removeFolderFailed = "Could not remove folder."removeFolderFailedDetail = "Could not remove folder: {{message}}"+retryFailed = "Could not retry {{name}}."+retryFailedDetail = "Could not retry {{name}}: {{message}}"+revertAllFailed = "Could not restore originals."+revertAllFailedDetail = "Could not restore originals: {{message}}"+revertFailed = "Could not restore {{name}}."+revertFailedDetail = "Could not restore {{name}}: {{message}}"uploadFilesFailed = "Could not upload files."uploadFilesFailedDetail = "Could not upload files: {{message}}"@@ -4554,6 +4574,32 @@ localHint = "Only stored in this browser"shared = "Shared"sharedHint = "Shared with you via link"+[filesPage.processing]+active = "Processing folder"+edit = "Edit processing..."+nothingToRestore = "No originals to restore - these files are already their originals."+paused = "Processing paused"+remove = "Remove processing"+restore = "Restore original"+restoreAll = "Restore all originals"+resume = "Resume processing"+revertCancel = "Cancel"+revertConfirm = "Restore and pause"+revertConfirmAll = "Restore every original in this folder? Processing will be paused, and restored files show as queued until you resume."+revertConfirmFile = "Restore \"{{name}}\" to its original? Processing for this folder will be paused, and the file shows as queued until you resume."+revertConfirmTitle = "Restore originals?"+section = "Processing"+start = "Process files in this folder..."+stop = "Pause processing"+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"label = "Filter files by name"@@ -9146,6 +9192,7 @@ paused = "Paused"[portal.policies.wizard.actions]cancel = "Cancel"customise = "Customise"+customiseUnavailable = "The full builder lives on Processor"enablePolicy = "Create pipeline"saveChanges = "Save changes"@@ -9788,6 +9835,39 @@ unlimited = "{{used}} · Unlimited"[printFile]title = "Print File"+[processingFolders.downloads]+approve = "Process my Downloads"+cancelSweep = "Cancel"+capped = "You have {{found}} PDFs; the first {{limit}} are processed now and the rest follow."+close = "Done"+explain_one = "Stirling can classify the {{count}} PDF already in your Downloads folder and open the results here."+explain_other = "Stirling can classify the {{count}} PDFs already in your Downloads folder and open the results here."+failed = "Could not set that up. Your files have not been changed."+finished_one = "Classified {{count}} file and opened {{opened}} of them here, ready to work on."+finished_other = "Classified {{count}} files and opened {{opened}} of them here, ready to work on."+keepsOriginals = "Files are processed in place - and each original is kept, so you can restore it any time."+nothingNew_one = "Nothing new to process - this {{count}} file has already been through."+nothingNew_other = "Nothing new to process - these {{count}} files have already been through."+notNow = "Not now"+progressCounts = "of {{total}} processed"+someFailed_one = "{{count}} could not be processed and was left untouched."+someFailed_other = "{{count}} could not be processed and were left untouched."+stillParked_one = "{{count}} file failed earlier and was not retried - fix the cause, then run again."+stillParked_other = "{{count}} files failed earlier and were not retried - fix the cause, then run again."+stillRunning = "Some files are still being processed in the background."+title = "Organize your Downloads?"+trigger_one = "Process {{count}} PDF in Downloads"+trigger_other = "Process {{count}} PDFs in Downloads"+typesFound_one = "{{count}} document type found"+typesFound_other = "{{count}} document types found"+working = "Processing ..."++[processingFolders.wall]+done = "Done"+failed = "Failed"+title = "Processing this folder"+waiting = "Queued ..."+[provider.googledrive]name = "Google Drive"scope = "File Import"@@ -12245,7 +12325,7 @@ changeFolder = "Change"chooseFolder = "Choose"clearFolder = "Clear"color = "Accent color"-createFolder = "Create Folder"+createFolder = "New folder"createTitle = "New Watched Folder"editTitle = "Edit Watched Folder"inputFolder = "Input folder"diff --git a/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsx b/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsxindex 08811f0053..0a4776d203 100644--- a/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsx+++ b/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsx@@ -4,7 +4,7 @@ import { Alert, Checkbox, Group, Modal, Stack, Text } from "@mantine/core";import ErrorOutlineIcon from "@mui/icons-material/ErrorOutlined";import { Button } from "@app/ui/Button";-import { FolderRecord } from "@app/types/folder";+import { folderKind, FolderRecord } from "@app/types/folder";interface DeleteFolderDialogProps {opened: boolean;@@ -37,22 +37,35 @@ export function DeleteFolderDialog({}, [opened]);if (!folder) return null;+ // A mount is a mapping, not storage: removing it never touches the disk, so+ // the dialog must not read like a deletion or offer to delete contents.+ const isMount = folderKind(folder) === "local";return (<Modalopened={opened}onClose={onClose}- title={t("filesPage.deleteFolderTitle", "Delete folder?")}+ title={+ isMount+ ? t("filesPage.unmountFolderTitle", "Unmount from Stirling?")+ : t("filesPage.deleteFolderTitle", "Delete folder?")+ }centeredsize="md"><Stack gap="md"><Text size="sm">- {t("filesPage.deleteFolderBody", 'Delete folder "{{name}}"?', {- name: folder.name,- })}+ {isMount+ ? t(+ "filesPage.unmountFolderBody",+ 'Unmount "{{name}}"? The folder and its files stay on your disk.',+ { name: folder.name },+ )+ : t("filesPage.deleteFolderBody", 'Delete folder "{{name}}"?', {+ name: folder.name,+ })}</Text>- {fileCount > 0 && (+ {!isMount && fileCount > 0 && (<Checkboxchecked={deleteContents}onChange={(e) => setDeleteContents(e.currentTarget.checked)}@@ -64,7 +77,7 @@ export function DeleteFolderDialog({)}/>)}- {fileCount > 0 && (+ {!isMount && fileCount > 0 && (<Text size="xs" c="dimmed">{deleteContents? t(@@ -114,7 +127,9 @@ export function DeleteFolderDialog({}}}>- {t("filesPage.delete", "Delete")}+ {isMount+ ? t("filesPage.unmount", "Unmount")+ : t("filesPage.delete", "Delete")}</Button></Group></Stack>diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.tsxindex 7fc393edb5..73606ad1e2 100644--- a/frontend/editor/src/core/components/filesPage/FileGrid.tsx+++ b/frontend/editor/src/core/components/filesPage/FileGrid.tsx@@ -1,6 +1,12 @@-import React, { useCallback, useMemo, useRef } from "react";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { useTranslation } from "react-i18next";-import { Checkbox, Menu, Tooltip } from "@mantine/core";+import { Checkbox, Loader, Menu, Tooltip } from "@mantine/core";import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";import MoreVertIcon from "@mui/icons-material/MoreVert";@@ -14,6 +20,12 @@ import DeleteIcon from "@mui/icons-material/Delete";import HistoryIcon from "@mui/icons-material/History";import OpenInNewIcon from "@mui/icons-material/OpenInNew";import DriveFileRenameOutlineIcon from "@mui/icons-material/DriveFileRenameOutline";+import AutoModeIcon from "@mui/icons-material/AutoMode";+import PlayArrowIcon from "@mui/icons-material/PlayArrow";+import PauseIcon from "@mui/icons-material/Pause";+import ReplayIcon from "@mui/icons-material/Replay";+import TuneIcon from "@mui/icons-material/Tune";+import TaskAltIcon from "@mui/icons-material/TaskAlt";import ContentCopyOutlinedIcon from "@mui/icons-material/ContentCopyOutlined";import CloudUploadIcon from "@mui/icons-material/CloudUpload";import UploadFileIcon from "@mui/icons-material/UploadFile";@@ -28,6 +40,10 @@ import {} from "@app/types/folder";import type { DiskFileEntry } from "@app/services/localFolderContents";import { usePolicyFileBadges } from "@app/hooks/usePolicyFileBadges";+import {+ useProcessingFolders,+ type ProcessingFolderState,+} from "@app/hooks/useProcessingFolders";import {useVirtualFileRows,rowHeightPx,@@ -95,6 +111,9 @@ function useFolderOriginBadge(folder: FolderRecord): {export type FilesPageViewMode = "grid" | "list";+/** A disk file's place in its working folder's pipeline, when one is attached. */+export type DiskFileState = "done" | "processing" | "failed" | "waiting";+export interface FilesPageEntry {kind: "folder" | "file" | "diskFile";folder?: FolderRecord;@@ -103,6 +122,9 @@ export interface FilesPageEntry {file?: StirlingFileStub;/** A file read straight off a mounted directory (kind "diskFile"). */disk?: DiskFileEntry;+ /** The disk file's processing state; absent on a folder with no pipeline. */+ diskState?: DiskFileState;+ hasOriginal?: boolean;/** Parent breadcrumb path for search results outside the current folder. */parentPath?: string;}@@ -120,6 +142,14 @@ interface FileGridProps {/** "Add to workspace". */onOpenFile: (file: StirlingFileStub) => void;onOpenDiskFile?: (entry: DiskFileEntry) => void;+ /** Open the processing-setup dialog for a folder (create or edit). */+ onStartProcessing?: (folder: FolderRecord) => void;+ /** Retry one failed file, by its name in the open folder. */+ onRetryFile?: (name: string) => void;+ /** Restore one file's archived original, by its name in the open folder. */+ onRevertFile?: (name: string) => void;+ /** Ask to restore every original in a folder; the confirm dialog lives upstream. */+ onRequestRevertAll?: (folder: FolderRecord) => void;onMoveFiles: (fileIds: FileId[],targetFolderId: FolderId | null,@@ -188,6 +218,12 @@ interface FileGridActions {openFolder: (id: FolderId) => void;openFile: (file: StirlingFileStub) => void;openDiskFile: (entry: DiskFileEntry) => void;+ startProcessing: (folder: FolderRecord) => void;+ retryFile: (name: string) => void;+ revertFile: (name: string) => void;+ requestRevertAll: (folder: FolderRecord) => void;+ /** Surface a failed folder action's reason the way a failed drop's is. */+ reportError: (err: unknown, label: string) => void;renameFolder: (folder: FolderRecord) => void;deleteFolder: (folder: FolderRecord) => void;changeFolderAppearance: (@@ -258,6 +294,11 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {openFolder: (id) => latest.current.onOpenFolder(id),openFile: (file) => latest.current.onOpenFile(file),openDiskFile: (entry) => latest.current.onOpenDiskFile?.(entry),+ startProcessing: (folder) => latest.current.onStartProcessing?.(folder),+ retryFile: (name) => latest.current.onRetryFile?.(name),+ revertFile: (name) => latest.current.onRevertFile?.(name),+ requestRevertAll: (folder) => latest.current.onRequestRevertAll?.(folder),+ reportError: (err, label) => reportDrop(err, label),renameFolder: (folder) => latest.current.onRenameFolder(folder),deleteFolder: (folder) => latest.current.onDeleteFolder(folder),changeFolderAppearance: (folderId, appearance) =>@@ -555,6 +596,8 @@ function GridView({<DiskFileCardkey={`disk-${entry.disk.path}`}entry={entry.disk}+ state={entry.diskState}+ hasOriginal={entry.hasOriginal}actions={actions}/>);@@ -565,6 +608,7 @@ function GridView({key={`file-${entry.file.id}`}file={entry.file}parentPath={entry.parentPath}+ processingState={entry.diskState}isSelected={selectedFileIds.has(entry.file.id)}isInWorkspace={activeWorkspaceFileIds?.has(entry.file.id) ?? false@@ -615,6 +659,33 @@ const FolderCard = React.memo(function FolderCard({// Only a server folder can go offline: the other kinds take their name, look and// lifetime from elsewhere, so their edit items are hidden rather than disabled.const kind = folderKind(folder);+ const {+ stateFor: processingStateFor,+ enable: enableProcessing,+ disable: disableProcessing,+ remove: removeProcessingFolder,+ sweep: sweepProcessing,+ listFiles: listProcessingFiles,+ } = useProcessingFolders();+ const processing = processingStateFor(folder);+ // Each action surfaces its own failure the way a failed drop does; the+ // backend's reason (invalid pipeline, storage disabled) is the useful part.+ const resumeProcessing = (label: string) =>+ Promise.resolve(enableProcessing(folder)).catch((err) =>+ actions.reportError(err, label),+ );+ const stopProcessing = (label: string) =>+ Promise.resolve(disableProcessing(folder)).catch((err) =>+ actions.reportError(err, label),+ );+ const runProcessing = (label: string) =>+ Promise.resolve(sweepProcessing(folder)).catch((err) =>+ actions.reportError(err, label),+ );+ const removeProcessing = (label: string) =>+ Promise.resolve(removeProcessingFolder(folder)).catch((err) =>+ actions.reportError(err, label),+ );const originBadge = useFolderOriginBadge(folder);const editsDisabled = kind === "server" && !serverReachable;const editsHidden = kind === "local";@@ -691,12 +762,36 @@ const FolderCard = React.memo(function FolderCard({</div>)}<div className="files-page-card-meta">- {fileCount === 0- ? t("filesPage.folder", "Folder")- : t("filesPage.folderItems", "{{count}} items", {- count: fileCount,- })}+ {processing ? (+ <>+ <span className="files-page-processing-tag">+ {processing.enabled+ ? t("filesPage.processing.active", "Processing folder")+ : t("filesPage.processing.paused", "Processing paused")}+ </span>+ {fileCount > 0 && (+ <span>+ {" · "}+ {t("filesPage.folderItems", "{{count}} items", {+ count: fileCount,+ })}+ </span>+ )}+ </>+ ) : fileCount === 0 ? (+ t("filesPage.folder", "Folder")+ ) : (+ t("filesPage.folderItems", "{{count}} items", {+ count: fileCount,+ })+ )}</div>+ {processing && (+ <ProcessingFolderStats+ recordId={processing.id}+ listFiles={listProcessingFiles}+ />+ )}</div><div className="files-page-card-actions"><Menu shadow="md" position="bottom-end" withinPortal>@@ -717,6 +812,25 @@ const FolderCard = React.memo(function FolderCard({>{t("filesPage.open", "Open")}</Menu.Item>+ {editsHidden && (+ <ProcessingMenuItems+ processing={processing}+ disabled={false}+ onRun={() => void runProcessing("process folder now")}+ onStop={() => void stopProcessing("pause processing folder")}+ onStart={() => actions.startProcessing(folder)}+ onResume={() => void resumeProcessing("resume processing")}+ onRevertAll={+ kind === "local"+ ? () => actions.requestRevertAll(folder)+ : undefined+ }+ onEdit={() => actions.startProcessing(folder)}+ onRemove={() =>+ void removeProcessing("remove processing folder")+ }+ />+ )}{/* Only a mount root can be removed; a subdirectory is thedisk's, and the app never deletes directories. */}{editsHidden && folder.parentFolderId === null && (@@ -725,10 +839,7 @@ const FolderCard = React.memo(function FolderCard({leftSection={<DeleteIcon fontSize="small" />}onClick={() => actions.deleteFolder(folder)}>- {t(- "filesPage.removeLocalFolder",- "Remove (files stay on disk)",- )}+ {t("filesPage.removeLocalFolder", "Unmount from Stirling")}</Menu.Item>)}{!editsHidden && (@@ -753,6 +864,21 @@ const FolderCard = React.memo(function FolderCard({disabled={editsDisabled}/><Menu.Divider />+ <ProcessingMenuItems+ processing={processing}+ continuous={kind === "virtual"}+ disabled={editsDisabled}+ disabledHint={offlineHint}+ onRun={() => void runProcessing("process folder now")}+ onStop={() => void stopProcessing("pause processing folder")}+ onStart={() => actions.startProcessing(folder)}+ onResume={() => void resumeProcessing("resume processing")}+ onEdit={() => actions.startProcessing(folder)}+ onRemove={() =>+ void removeProcessing("remove processing folder")+ }+ />+ <Menu.Divider /><Menu.Itemcolor="red"leftSection={<DeleteIcon fontSize="small" />}@@ -771,6 +897,240 @@ const FolderCard = React.memo(function FolderCard({);});+/**+ * A working folder's live per-state counts on its card. Light polling: a handful of+ * processing folders at most, and the numbers are the card's whole story.+ */+function ProcessingFolderStats({+ recordId,+ listFiles,+}: {+ recordId: string;+ listFiles: (recordId: string) => Promise<{ state: string }[]>;+}) {+ const { t } = useTranslation();+ const [counts, setCounts] = useState<Record<string, number> | null>(null);+ useEffect(() => {+ let cancelled = false;+ const tick = async () => {+ const files = await listFiles(recordId).catch(() => []);+ if (cancelled) return;+ const next: Record<string, number> = {};+ for (const file of files) {+ next[file.state] = (next[file.state] ?? 0) + 1;+ }+ setCounts(next);+ };+ void tick();+ const timer = setInterval(() => void tick(), 5000);+ return () => {+ cancelled = true;+ clearInterval(timer);+ };+ }, [recordId, listFiles]);+ if (!counts) return null;+ const parts = (+ [+ ["done", t("filesPage.diskState.done", "Ready")],+ ["processing", t("filesPage.diskState.processing", "Processing")],+ ["failed", t("filesPage.diskState.failed", "Failed")],+ ["waiting", t("filesPage.diskState.waiting", "Queued")],+ ] as const+ ).filter(([state]) => (counts[state] ?? 0) > 0);+ if (parts.length === 0) return null;+ return (+ <div className="files-page-folder-stats">+ {parts.map(([state, label]) => (+ <span key={state} className={`files-page-folder-stat is-${state}`}>+ {counts[state]} {label}+ </span>+ ))}+ </div>+ );+}++/**+ * The processing entries of a folder's action menu, carried by every folder kind including+ * mounts, whose other edit actions are hidden. `continuous` marks a folder whose engine+ * processes arrivals on its own, where an explicit "process now" would have nothing to do.+ */+export function ProcessingMenuItems({+ processing,+ continuous = false,+ disabled,+ disabledHint,+ onRun,+ onStop,+ onStart,+ onResume,+ onRemove,+ onEdit,+ onRevertAll,+}: {+ processing: ProcessingFolderState | undefined;+ continuous?: boolean;+ disabled: boolean;+ disabledHint?: string;+ onRun: () => void;+ onStop: () => void;+ onStart: () => void;+ onResume: () => void;+ onRemove: () => void;+ /** Open the setup dialog seeded from the existing record; absent hides Edit. */+ onEdit?: () => void;+ /** Restore every archived original in the folder; absent hides the entry. */+ onRevertAll?: () => void;+}) {+ const { t } = useTranslation();+ const heading = (+ <Menu.Label>{t("filesPage.processing.section", "Processing")}</Menu.Label>+ );+ if (!processing) {+ return (+ <>+ {heading}+ <Menu.Item+ leftSection={<AutoModeIcon fontSize="small" />}+ onClick={onStart}+ disabled={disabled}+ title={disabled ? disabledHint : undefined}+ >+ {t("filesPage.processing.start", "Process files in this folder...")}+ </Menu.Item>+ </>+ );+ }+ if (!processing.enabled) {+ // Paused, not gone: the pair kept its history, so resuming never re-runs+ // what was already done. Removing is the destructive option, named as such.+ return (+ <>+ {heading}+ <Menu.Item+ leftSection={<PlayArrowIcon fontSize="small" />}+ onClick={onResume}+ disabled={disabled}+ title={disabled ? disabledHint : undefined}+ >+ {t("filesPage.processing.resume", "Resume processing")}+ </Menu.Item>+ {onEdit && (+ <Menu.Item+ leftSection={<TuneIcon fontSize="small" />}+ onClick={onEdit}+ disabled={disabled}+ title={disabled ? disabledHint : undefined}+ >+ {t("filesPage.processing.edit", "Edit processing...")}+ </Menu.Item>+ )}+ {onRevertAll && (+ <Menu.Item+ leftSection={<HistoryIcon fontSize="small" />}+ onClick={onRevertAll}+ disabled={disabled}+ title={disabled ? disabledHint : undefined}+ >+ {t("filesPage.processing.restoreAll", "Restore all originals")}+ </Menu.Item>+ )}+ <Menu.Item+ color="red"+ leftSection={<AutoModeIcon fontSize="small" />}+ onClick={onRemove}+ disabled={disabled}+ title={disabled ? disabledHint : undefined}+ >+ {t("filesPage.processing.remove", "Remove processing")}+ </Menu.Item>+ </>+ );+ }+ return (+ <>+ {heading}+ {!continuous && (+ <Menu.Item+ leftSection={<ReplayIcon fontSize="small" />}+ onClick={onRun}+ >+ {t("filesPage.processing.sweep", "Retry failed files")}+ </Menu.Item>+ )}+ <Menu.Item leftSection={<PauseIcon fontSize="small" />} onClick={onStop}>+ {t("filesPage.processing.stop", "Pause processing")}+ </Menu.Item>+ {onEdit && (+ <Menu.Item leftSection={<TuneIcon fontSize="small" />} onClick={onEdit}>+ {t("filesPage.processing.edit", "Edit processing...")}+ </Menu.Item>+ )}+ {onRevertAll && (+ <Menu.Item+ leftSection={<HistoryIcon fontSize="small" />}+ onClick={onRevertAll}+ >+ {t("filesPage.processing.restoreAll", "Restore all originals")}+ </Menu.Item>+ )}+ </>+ );+}++/** A file's pipeline state chip; a failed state adds an inline retry. */+function FileStateBadge({+ state,+ onRetry,+}: {+ state?: DiskFileState;+ onRetry?: () => void;+}) {+ const { t } = useTranslation();+ if (!state) return null;+ if (state === "done") {+ return (+ <span className="files-page-state-badge is-done">+ <TaskAltIcon style={{ fontSize: "0.85rem" }} />+ {t("filesPage.diskState.done", "Ready")}+ </span>+ );+ }+ if (state === "processing") {+ return (+ <span className="files-page-state-badge">+ <Loader size="0.7rem" />+ {t("filesPage.diskState.processing", "Processing")}+ </span>+ );+ }+ if (state === "failed") {+ return (+ <span className="files-page-state-badge is-failed">+ {t("filesPage.diskState.failed", "Failed")}+ {onRetry && (+ <button+ type="button"+ className="files-page-state-retry"+ onClick={(e) => {+ e.stopPropagation();+ onRetry();+ }}+ title={t("filesPage.diskState.retryHint", "Run this file again")}+ >+ <ReplayIcon style={{ fontSize: "0.8rem" }} />+ {t("filesPage.diskState.retry", "Retry")}+ </button>+ )}+ </span>+ );+ }+ return (+ <span className="files-page-state-badge">+ {t("filesPage.diskState.waiting", "Queued")}+ </span>+ );+}+/** Stable empty value so badge-less rows keep identical props across renders. */const NO_BADGES: FileItemPolicyRef[] = [];@@ -962,6 +1322,7 @@ interface FileCardProps {/** When set, the kebab Save to server is disabled with this tooltip. */saveToServerDisabledReason?: string | null;badges: FileItemPolicyRef[];+ processingState?: DiskFileState;actions: FileGridActions;}@@ -978,6 +1339,7 @@ const FileCard = React.memo(function FileCard({versionHistoryAvailable,saveToServerDisabledReason,badges,+ processingState,actions,}: FileCardProps) {const { t } = useTranslation();@@ -1092,6 +1454,10 @@ const FileCard = React.memo(function FileCard({<div className="files-page-card-origin"><FileOriginBadge origin={getFileOrigin(file)} compact /></div>+ <FileStateBadge+ state={processingState}+ onRetry={() => actions.retryFile(file.name)}+ /></div><div className="files-page-card-body"><div className="files-page-card-name" title={file.name}>@@ -1268,6 +1634,8 @@ function ListView({<DiskFileRowkey={`disk-${entry.disk.path}`}entry={entry.disk}+ state={entry.diskState}+ hasOriginal={entry.hasOriginal}actions={actions}/>);@@ -1278,6 +1646,7 @@ function ListView({key={`file-${entry.file.id}`}file={entry.file}parentPath={entry.parentPath}+ processingState={entry.diskState}isSelected={selectedFileIds.has(entry.file.id)}isInWorkspace={activeWorkspaceFileIds?.has(entry.file.id) ?? false@@ -1326,6 +1695,32 @@ const FolderRow = React.memo(function FolderRow({const onOpen = () => actions.openFolder(folder.id);// Kinds gate the edit items, as in FolderCard.const kind = folderKind(folder);+ const {+ stateFor: processingStateFor,+ enable: enableProcessing,+ disable: disableProcessing,+ remove: removeProcessingFolder,+ sweep: sweepProcessing,+ } = useProcessingFolders();+ const processing = processingStateFor(folder);+ // Each action surfaces its own failure the way a failed drop does; the+ // backend's reason (invalid pipeline, storage disabled) is the useful part.+ const resumeProcessing = (label: string) =>+ Promise.resolve(enableProcessing(folder)).catch((err) =>+ actions.reportError(err, label),+ );+ const stopProcessing = (label: string) =>+ Promise.resolve(disableProcessing(folder)).catch((err) =>+ actions.reportError(err, label),+ );+ const runProcessing = (label: string) =>+ Promise.resolve(sweepProcessing(folder)).catch((err) =>+ actions.reportError(err, label),+ );+ const removeProcessing = (label: string) =>+ Promise.resolve(removeProcessingFolder(folder)).catch((err) =>+ actions.reportError(err, label),+ );const originBadge = useFolderOriginBadge(folder);const editsDisabled = kind === "server" && !serverReachable;const editsHidden = kind === "local";@@ -1413,11 +1808,19 @@ const FolderRow = React.memo(function FolderRow({/></span><span role="gridcell">- {kind === "virtual"- ? t("filesPage.folderKind.virtual", "Browser folder")- : kind === "local"- ? t("filesPage.folderKind.local", "Local folder")- : t("filesPage.folder", "Folder")}+ {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@@ -1447,6 +1850,25 @@ const FolderRow = React.memo(function FolderRow({>{t("filesPage.open", "Open")}</Menu.Item>+ {editsHidden && (+ <ProcessingMenuItems+ processing={processing}+ disabled={false}+ onRun={() => void runProcessing("process folder now")}+ onStop={() => void stopProcessing("pause processing folder")}+ onStart={() => actions.startProcessing(folder)}+ onResume={() => void resumeProcessing("resume processing")}+ onRevertAll={+ kind === "local"+ ? () => actions.requestRevertAll(folder)+ : undefined+ }+ onEdit={() => actions.startProcessing(folder)}+ onRemove={() =>+ void removeProcessing("remove processing folder")+ }+ />+ )}{/* Only a mount root can be removed; a subdirectory is thedisk's, and the app never deletes directories. */}{editsHidden && folder.parentFolderId === null && (@@ -1455,10 +1877,7 @@ const FolderRow = React.memo(function FolderRow({leftSection={<DeleteIcon fontSize="small" />}onClick={() => actions.deleteFolder(folder)}>- {t(- "filesPage.removeLocalFolder",- "Remove (files stay on disk)",- )}+ {t("filesPage.removeLocalFolder", "Unmount from Stirling")}</Menu.Item>)}{!editsHidden && (@@ -1483,6 +1902,21 @@ const FolderRow = React.memo(function FolderRow({disabled={editsDisabled}/><Menu.Divider />+ <ProcessingMenuItems+ processing={processing}+ continuous={kind === "virtual"}+ disabled={editsDisabled}+ disabledHint={offlineHint}+ onRun={() => void runProcessing("process folder now")}+ onStop={() => void stopProcessing("pause processing folder")}+ onStart={() => actions.startProcessing(folder)}+ onResume={() => void resumeProcessing("resume processing")}+ onEdit={() => actions.startProcessing(folder)}+ onRemove={() =>+ void removeProcessing("remove processing folder")+ }+ />+ <Menu.Divider /><Menu.Itemcolor="red"leftSection={<DeleteIcon fontSize="small" />}@@ -1519,6 +1953,7 @@ interface FileRowProps {/** When set, the kebab Save to server is disabled with this tooltip. */saveToServerDisabledReason?: string | null;badges: FileItemPolicyRef[];+ processingState?: DiskFileState;actions: FileGridActions;}@@ -1535,6 +1970,7 @@ const FileRow = React.memo(function FileRow({versionHistoryAvailable,saveToServerDisabledReason,badges,+ processingState,actions,}: FileRowProps) {const { t } = useTranslation();@@ -1659,6 +2095,10 @@ const FileRow = React.memo(function FileRow({</span><FileOriginBadge origin={getFileOrigin(file)} compact /><PolicyBadgeRow policies={badges} />+ <FileStateBadge+ state={processingState}+ onRetry={() => actions.retryFile(file.name)}+ />{isInWorkspace && (<span className="files-page-row-open-pill"><span className="files-page-card-open-dot" />@@ -1695,12 +2135,21 @@ export { ROOT_FOLDER_ID };*/const DiskFileCard = React.memo(function DiskFileCard({entry,+ state,+ hasOriginal,actions,}: {entry: DiskFileEntry;+ state?: DiskFileState;+ hasOriginal?: boolean;actions: FileGridActions;}) {- const onOpen = () => actions.openDiskFile(entry);+ // A file mid-processing is locked: its bytes are about to be replaced, so opening+ // it would show a result that is not there yet.+ const locked = state === "processing";+ const onOpen = () => {+ if (!locked) actions.openDiskFile(entry);+ };const { t } = useTranslation();const thumbnail = useDiskThumbnail(entry);const extension = entry.name.includes(".")@@ -1709,14 +2158,21 @@ const DiskFileCard = React.memo(function DiskFileCard({const isPdf = extension === "PDF";return (<div- className="files-page-card"+ className={`files-page-card${locked ? " is-locked" : ""}`}role="listitem"tabIndex={0}onDoubleClick={onOpen}onKeyDown={(e) => {if (e.key === "Enter") onOpen();}}- title={entry.path}+ title={+ locked+ ? t(+ "filesPage.diskState.processingHint",+ "Processing - available when it finishes",+ )+ : entry.path+ }><div className="files-page-card-thumb">{thumbnail ? (@@ -1741,6 +2197,10 @@ const DiskFileCard = React.memo(function DiskFileCard({compact/></div>+ <FileStateBadge+ state={state}+ onRetry={() => actions.retryFile(entry.name)}+ /></div><div className="files-page-card-body"><div className="files-page-card-name" title={entry.name}>@@ -1773,6 +2233,17 @@ const DiskFileCard = React.memo(function DiskFileCard({>{t("filesPage.addToWorkspace", "Add to workspace")}</Menu.Item>+ {hasOriginal && (+ <Menu.Item+ leftSection={<HistoryIcon fontSize="small" />}+ onClick={(e) => {+ e.stopPropagation();+ actions.revertFile(entry.name);+ }}+ >+ {t("filesPage.processing.restore", "Restore original")}+ </Menu.Item>+ )}</Menu.Dropdown></Menu></div>@@ -1783,12 +2254,21 @@ const DiskFileCard = React.memo(function DiskFileCard({/** List-view sibling of {@link DiskFileCard}; same single affordance. */const DiskFileRow = React.memo(function DiskFileRow({entry,+ state,+ hasOriginal,actions,}: {entry: DiskFileEntry;+ state?: DiskFileState;+ hasOriginal?: boolean;actions: FileGridActions;}) {- const onOpen = () => actions.openDiskFile(entry);+ // A file mid-processing is locked: its bytes are about to be replaced, so opening+ // it would show a result that is not there yet.+ const locked = state === "processing";+ const onOpen = () => {+ if (!locked) actions.openDiskFile(entry);+ };const { t } = useTranslation();const thumbnail = useDiskThumbnail(entry);const ext = entry.name.includes(".")@@ -1798,7 +2278,7 @@ const DiskFileRow = React.memo(function DiskFileRow({<divrole="row"tabIndex={0}- className="files-page-list-row"+ className={`files-page-list-row${locked ? " is-locked" : ""}`}onDoubleClick={onOpen}onKeyDown={(e) => {if (e.key === "Enter") onOpen();@@ -1850,6 +2330,10 @@ const DiskFileRow = React.memo(function DiskFileRow({)}compact/>+ <FileStateBadge+ state={state}+ onRetry={() => actions.retryFile(entry.name)}+ /></span><span role="gridcell">{ext || t("filesPage.file", "File")}</span><span role="gridcell">{formatFileSize(entry.sizeBytes)}</span>@@ -1875,6 +2359,14 @@ const DiskFileRow = React.memo(function DiskFileRow({>{t("filesPage.addToWorkspace", "Add to workspace")}</Menu.Item>+ {hasOriginal && (+ <Menu.Item+ leftSection={<HistoryIcon fontSize="small" />}+ onClick={() => actions.revertFile(entry.name)}+ >+ {t("filesPage.processing.restore", "Restore original")}+ </Menu.Item>+ )}</Menu.Dropdown></Menu></span>diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsxindex 774fbdb0a0..3da8f6a202 100644--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx@@ -66,11 +66,29 @@ import { StirlingFileStub } from "@app/types/fileContext";import {FolderBreadcrumbEntry,FolderId,+ FolderRecord,ROOT_FOLDER_ID,folderKind,} from "@app/types/folder";-import { FileGrid, FilesPageEntry } from "@app/components/filesPage/FileGrid";+import {+ FileGrid,+ FilesPageEntry,+ type DiskFileState,+} from "@app/components/filesPage/FileGrid";+import AutoModeIcon from "@mui/icons-material/AutoMode";+import PlayArrowIcon from "@mui/icons-material/PlayArrow";+import PauseIcon from "@mui/icons-material/Pause";+import ReplayIcon from "@mui/icons-material/Replay";+import TuneIcon from "@mui/icons-material/Tune";+import HistoryIcon from "@mui/icons-material/History";+import PaletteIcon from "@mui/icons-material/Palette";+import DriveFileRenameOutlineIcon from "@mui/icons-material/DriveFileRenameOutline";+import { FolderAppearancePicker } from "@app/components/filesPage/FolderAppearancePicker";+import { useProcessingFolders } from "@app/hooks/useProcessingFolders";+import { FolderProcessingSetup } from "@app/components/policies/FolderProcessingSetup";+import { FolderSweepWall } from "@app/components/policies/SweepRunWall";+import { RestoreOriginalsDialog } from "@app/components/filesPage/RestoreOriginalsDialog";import SuperSearch from "@app/components/shared/superSearch/SuperSearch";import { useEditorSearchScopes } from "@app/hooks/useSuperSearch";import { FileDetailsPanel } from "@app/components/filesPage/FileDetailsPanel";@@ -474,6 +492,11 @@ export default function FileManagerView() {currentFolder && folderKind(currentFolder) === "local"? currentFolder.directory: undefined;+ const headerEditsDisabled = Boolean(+ currentFolder &&+ folderKind(currentFolder) === "server" &&+ !folders.serverReachable,+ );const { setError: setFolderError, registerDiskSubfolders } = folders;const [diskEntries, setDiskEntries] = useState<DiskFileEntry[]>([]);const [diskLoading, setDiskLoading] = useState(false);@@ -488,11 +511,17 @@ export default function FileManagerView() {return;}let cancelled = false;- setDiskLoading(true);- listDirectory(currentLocalDirectory)- .then((listed) => {+ // The directory is the disk's and anything can write to it, so poll while open and let+ // outside changes appear on their own; only a changed listing re-renders.+ const load = async (background: boolean) => {+ if (!background) setDiskLoading(true);+ try {+ const listed = await listDirectory(currentLocalDirectory);if (cancelled) return;- setDiskEntries(listed?.files ?? []);+ const files = listed?.files ?? [];+ setDiskEntries((prev) =>+ listingSignature(prev) === listingSignature(files) ? prev : files,+ );if (currentFolderId !== null) {registerDiskSubfolders(currentFolderId,@@ -508,10 +537,11 @@ export default function FileManagerView() {})),);}- })- .catch((err) => {+ } catch (err) {console.warn("[FileManagerView] disk listing failed", err);- if (!cancelled) {+ // Background ticks stay quiet: a transient lock (a sync client holding+ // the directory) would otherwise pop an error banner every few seconds.+ if (!cancelled && !background) {setDiskEntries([]);setFolderError(err instanceof Error@@ -525,12 +555,15 @@ export default function FileManagerView() {),);}- })- .finally(() => {- if (!cancelled) setDiskLoading(false);- });+ } finally {+ if (!cancelled && !background) setDiskLoading(false);+ }+ };+ void load(false);+ const timer = setInterval(() => void load(true), 4000);return () => {cancelled = true;+ clearInterval(timer);};// The stable setter, not the context: its identity changes on every folder// mutation, including the setError above, so a failing listing would re-trigger.@@ -570,6 +603,201 @@ export default function FileManagerView() {[addFiles, navActions, navigate, folders, t],);+ // A working folder lists its real contents; each file wears its pipeline state and a state+ // filter narrows the listing. Files the pipeline never claims carry no state at all.+ const processingApi = useProcessingFolders();+ const currentProcessing = currentFolder+ ? processingApi.stateFor(currentFolder)+ : undefined;+ const outputDirectory = currentLocalDirectory+ ? currentProcessing?.outputDirectory+ : undefined;+ // Per-file state from the backend's ledger: processing in place leaves no output folder to+ // infer it from. Polled while the folder is open so badges follow the sweep live.+ const [fileStates, setFileStates] = useState<Map<string, DiskFileState>>(+ new Map(),+ );+ // Files whose pre-processing original is archived and can be restored.+ const [revertables, setRevertables] = useState<ReadonlySet<string>>(+ new Set(),+ );+ const processingRecordId = currentProcessing?.id;+ // The state layer applies inside any working folder: a mount's directory listing or a+ // server folder's stored files, both joined to the same ledger behind listFiles.+ const processingView = Boolean(+ processingRecordId && (outputDirectory || !currentLocalDirectory),+ );+ const { listFiles, retryFile, revertFile } = processingApi;+ useEffect(() => {+ if (!processingView || !processingRecordId) {+ // Keep the empty value when it is already empty: a fresh Map/Set is never Object.is equal,+ // so setting one unconditionally re-renders, on every render of a folder with no processing.+ setFileStates((prev) => (prev.size === 0 ? prev : new Map()));+ setRevertables((prev) => (prev.size === 0 ? prev : new Set()));+ return;+ }+ let cancelled = false;+ const tick = async () => {+ const files = await listFiles(processingRecordId).catch(() => []);+ if (!cancelled) {+ setFileStates(new Map(files.map((f) => [f.name, f.state])));+ setRevertables(+ new Set(files.filter((f) => f.hasOriginal).map((f) => f.name)),+ );+ }+ };+ void tick();+ const timer = setInterval(() => void tick(), 3000);+ return () => {+ cancelled = true;+ clearInterval(timer);+ };+ }, [processingView, processingRecordId, listFiles]);++ const [processingSetupFolder, setProcessingSetupFolder] =+ useState<FolderRecord | null>(null);+ // Restores wait on a confirmation, since they also pause the folder.+ const [revertConfirmName, setRevertConfirmName] = useState<string | null>(+ null,+ );+ const [revertAllTarget, setRevertAllTarget] = useState<FolderRecord | null>(+ null,+ );++ const [diskStateFilter, setDiskStateFilter] = useState<DiskFileState | "all">(+ "all",+ );+ const diskStateFor = useCallback(+ (name: string): DiskFileState | undefined => fileStates.get(name),+ [fileStates],+ );+ // Counts for the filter chips, from the same states the badges wear.+ const stateCounts = useMemo(() => {+ const counts: Record<DiskFileState, number> = {+ done: 0,+ processing: 0,+ failed: 0,+ waiting: 0,+ };+ for (const state of fileStates.values()) counts[state] += 1;+ return counts;+ }, [fileStates]);+ const retryDiskFile = useCallback(+ (name: string) => {+ if (!processingRecordId) return;+ void retryFile(processingRecordId, name)+ .then(() =>+ // Show the retry took, ahead of the next poll.+ setFileStates((prev) => {+ const next = new Map(prev);+ next.set(name, "processing");+ return next;+ }),+ )+ .catch((err) =>+ folders.setError(+ err instanceof Error+ ? t("filesPage.error.retryFailedDetail", {+ name,+ message: err.message,+ defaultValue: `Could not retry ${name}: ${err.message}`,+ })+ : t("filesPage.error.retryFailed", {+ name,+ defaultValue: `Could not retry ${name}.`,+ }),+ ),+ );+ },+ [processingRecordId, retryFile, folders, t],+ );+ const revertFolderFile = useCallback(+ (name: string) => {+ if (!processingRecordId) return;+ void revertFile(processingRecordId, name)+ .then(() => {+ // Reflect the restore ahead of the next poll.+ setFileStates((prev) => {+ const next = new Map(prev);+ next.set(name, "waiting");+ return next;+ });+ setRevertables((prev) => {+ const next = new Set(prev);+ next.delete(name);+ return next;+ });+ })+ .catch((err) =>+ folders.setError(+ err instanceof Error+ ? t("filesPage.error.revertFailedDetail", {+ name,+ message: err.message,+ defaultValue: `Could not restore ${name}: ${err.message}`,+ })+ : t("filesPage.error.revertFailed", {+ name,+ defaultValue: `Could not restore ${name}.`,+ }),+ ),+ );+ },+ [processingRecordId, revertFile, folders, t],+ );+ const revertAllInFolder = useCallback(+ (folder: FolderRecord) => {+ void processingApi+ .revertAll(folder)+ .then((outcome) => {+ if (outcome && outcome.restored === 0 && outcome.skipped === 0) {+ folders.setError(+ t(+ "filesPage.processing.nothingToRestore",+ "No originals to restore - these files are already their originals.",+ ),+ );+ }+ })+ .catch((err) =>+ folders.setError(+ err instanceof Error+ ? t("filesPage.error.revertAllFailedDetail", {+ message: err.message,+ defaultValue: `Could not restore originals: ${err.message}`,+ })+ : t(+ "filesPage.error.revertAllFailed",+ "Could not restore originals.",+ ),+ ),+ );+ },+ [processingApi, folders, t],+ );+ // The open folder's own actions: everything its card kebab offers from the+ // listing outside must be reachable from inside the folder too.+ const runFolderAction = useCallback(+ (action: (folder: FolderRecord) => Promise<void>, label: string) => {+ if (!currentFolder) return;+ void action(currentFolder).catch((err) =>+ folders.setError(+ err instanceof Error+ ? t("filesPage.error.actionFailedDetail", {+ action: label,+ message: err.message,+ defaultValue: `Could not ${label}: ${err.message}`,+ })+ : t("filesPage.error.actionFailed", {+ action: label,+ defaultValue: `Could not ${label}.`,+ }),+ ),+ );+ },+ [currentFolder, folders, t],+ );+const entries = useMemo<FilesPageEntry[]>(() => {// When searching, items may come from anywhere in the subtree, so we// expose a "parentPath" subtitle whenever the item's parent differs from@@ -590,16 +818,31 @@ export default function FileManagerView() {"modified-asc": (a, b) => a.lastModified - b.lastModified,"modified-desc": (a, b) => b.lastModified - a.lastModified,};+ const toDiskEntries = (list: DiskFileEntry[]) =>+ list+ .filter((disk) => !needle || disk.name.toLowerCase().includes(needle))+ .sort(compare[filesPage.sortMode] ?? compare["modified-desc"]!)+ .map<FilesPageEntry>((disk) => ({+ kind: "diskFile",+ disk,+ diskState: outputDirectory ? diskStateFor(disk.name) : undefined,+ hasOriginal: outputDirectory+ ? revertables.has(disk.name)+ : undefined,+ }))+ .filter(+ (entry) =>+ diskStateFilter === "all" ||+ entry.diskState === undefined ||+ entry.diskState === diskStateFilter,+ );return [...visibleFolders.map<FilesPageEntry>((folder) => ({kind: "folder",folder,folderFileCount: 0,})),- ...diskEntries- .filter((disk) => !needle || disk.name.toLowerCase().includes(needle))- .sort(compare[filesPage.sortMode] ?? compare["modified-desc"]!)- .map<FilesPageEntry>((disk) => ({ kind: "diskFile", disk })),+ ...toDiskEntries(diskEntries),];}return [@@ -612,14 +855,22 @@ export default function FileManagerView() {? pathForFolderId(folder.parentFolderId) || undefined: undefined,})),- ...visibleFiles.map<FilesPageEntry>((file) => ({- kind: "file",- file,- parentPath:- inSearch && (file.folderId ?? null) !== (currentFolderId ?? null)- ? pathForFolderId(file.folderId ?? null) || undefined- : undefined,- })),+ ...visibleFiles+ .map<FilesPageEntry>((file) => ({+ kind: "file",+ file,+ diskState: processingView ? diskStateFor(file.name) : undefined,+ parentPath:+ inSearch && (file.folderId ?? null) !== (currentFolderId ?? null)+ ? pathForFolderId(file.folderId ?? null) || undefined+ : undefined,+ }))+ .filter(+ (entry) =>+ diskStateFilter === "all" ||+ entry.diskState === undefined ||+ entry.diskState === diskStateFilter,+ ),];}, [visibleFolders,@@ -629,6 +880,11 @@ export default function FileManagerView() {currentFolderId,currentLocalDirectory,diskEntries,+ outputDirectory,+ processingView,+ diskStateFor,+ revertables,+ diskStateFilter,filesPage.sortMode,pathForFolderId,]);@@ -1425,6 +1681,282 @@ export default function FileManagerView() {selectedCount={selectedFiles.length}selectionOnly={mobileSelection}/>+ {currentFolder && !mobileSelection && (+ <div className="files-page-folder-actions">+ {!currentProcessing ? (+ <Tooltip+ label={t(+ "filesPage.processing.start",+ "Process files in this folder...",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() => setProcessingSetupFolder(currentFolder)}+ aria-label={t(+ "filesPage.processing.start",+ "Process files in this folder...",+ )}+ >+ <AutoModeIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ ) : (+ <>+ {currentProcessing.enabled ? (+ <>+ {folderKind(currentFolder) !== "virtual" &&+ stateCounts.failed > 0 && (+ <Tooltip+ label={t(+ "filesPage.processing.sweep",+ "Retry failed files",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() =>+ runFolderAction(+ processingApi.sweep,+ "process folder now",+ )+ }+ aria-label={t(+ "filesPage.processing.sweep",+ "Retry failed files",+ )}+ >+ <ReplayIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ )}+ <Tooltip+ label={t(+ "filesPage.processing.stop",+ "Pause processing",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() =>+ runFolderAction(+ processingApi.disable,+ "pause processing folder",+ )+ }+ aria-label={t(+ "filesPage.processing.stop",+ "Pause processing",+ )}+ >+ <PauseIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ </>+ ) : (+ <Tooltip+ label={t(+ "filesPage.processing.resume",+ "Resume processing",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() =>+ runFolderAction(+ processingApi.enable,+ "resume processing",+ )+ }+ aria-label={t(+ "filesPage.processing.resume",+ "Resume processing",+ )}+ >+ <PlayArrowIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ )}+ <Tooltip+ label={t(+ "filesPage.processing.edit",+ "Edit processing...",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() => setProcessingSetupFolder(currentFolder)}+ aria-label={t(+ "filesPage.processing.edit",+ "Edit processing...",+ )}+ >+ <TuneIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ {folderKind(currentFolder) === "local" && (+ <Tooltip+ label={t(+ "filesPage.processing.restoreAll",+ "Restore all originals",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() => setRevertAllTarget(currentFolder)}+ aria-label={t(+ "filesPage.processing.restoreAll",+ "Restore all originals",+ )}+ >+ <HistoryIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ )}+ <Tooltip+ label={t(+ "filesPage.processing.remove",+ "Remove processing",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() =>+ runFolderAction(+ processingApi.remove,+ "remove processing folder",+ )+ }+ aria-label={t(+ "filesPage.processing.remove",+ "Remove processing",+ )}+ >+ <AutoModeIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ </>+ )}+ {folderKind(currentFolder) === "local" ? (+ currentFolder.parentFolderId === null && (+ <Tooltip+ label={t(+ "filesPage.removeLocalFolder",+ "Unmount from Stirling",+ )}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() => promptDeleteFolder(currentFolder)}+ aria-label={t(+ "filesPage.removeLocalFolder",+ "Unmount from Stirling",+ )}+ >+ <DeleteIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ )+ ) : (+ <>+ <Tooltip+ label={t("filesPage.rename", "Rename")}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() => openRenameFolderDialog(currentFolder)}+ disabled={headerEditsDisabled}+ aria-label={t("filesPage.rename", "Rename")}+ >+ <DriveFileRenameOutlineIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ <Menu shadow="md" position="bottom-start" withinPortal>+ <Menu.Target>+ <Tooltip+ label={t("filesPage.appearance.title", "Appearance")}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ disabled={headerEditsDisabled}+ aria-label={t(+ "filesPage.appearance.title",+ "Appearance",+ )}+ >+ <PaletteIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ </Menu.Target>+ <Menu.Dropdown>+ <FolderAppearancePicker+ folder={currentFolder}+ onChange={(appearance) => {+ setFolderAppearance(+ currentFolder.id,+ appearance,+ ).catch((err) =>+ folders.setError(+ err instanceof Error+ ? t(+ "filesPage.error.folderAppearanceFailedDetail",+ {+ message: err.message,+ defaultValue: `Could not update folder appearance: ${err.message}`,+ },+ )+ : t(+ "filesPage.error.folderAppearanceFailed",+ "Could not update folder appearance.",+ ),+ ),+ );+ }}+ disabled={headerEditsDisabled}+ />+ </Menu.Dropdown>+ </Menu>+ <Tooltip+ label={t("filesPage.deleteFolder", "Delete folder")}+ withinPortal+ >+ <ActionIcon+ size="sm"+ variant="secondary"+ onClick={() => promptDeleteFolder(currentFolder)}+ disabled={headerEditsDisabled}+ aria-label={t(+ "filesPage.deleteFolder",+ "Delete folder",+ )}+ >+ <DeleteIcon fontSize="small" />+ </ActionIcon>+ </Tooltip>+ </>+ )}+ </div>+ )}{(() => {// Select all / Clear toggle over visible files.if (visibleFiles.length === 0) return null;@@ -1847,6 +2379,31 @@ export default function FileManagerView() {className="files-page-content"onClick={handleContentBackgroundClick}>+ {processingView && (+ <div className="files-page-state-filters">+ {(+ ["all", "done", "processing", "failed", "waiting"] as const+ ).map((value) => (+ <button+ key={value}+ type="button"+ className={diskStateFilter === value ? "is-active" : ""}+ onClick={(e) => {+ e.stopPropagation();+ setDiskStateFilter(value);+ }}+ >+ {t(`filesPage.diskState.${value}`, value)}+ {value !== "all" && stateCounts[value] > 0 && (+ <span className="files-page-state-count">+ {stateCounts[value]}+ </span>+ )}+ </button>+ ))}+ </div>+ )}+ <FolderSweepWall policyId={processingRecordId} /><FileGridentries={entries}loading={loading || diskLoading}@@ -1862,7 +2419,11 @@ export default function FileManagerView() {onSelectFile={handleSelectFile}onSetSelection={setSelectedFileIds}onOpenFolder={handleOpenFolder}+ onStartProcessing={setProcessingSetupFolder}onOpenDiskFile={(entry) => void openDiskFile(entry)}+ onRetryFile={retryDiskFile}+ onRevertFile={setRevertConfirmName}+ onRequestRevertAll={setRevertAllTarget}onOpenFile={handleOpenFile}onMoveFiles={moveFilesTo}onMoveFolder={moveFolderTo}@@ -1955,6 +2516,23 @@ export default function FileManagerView() {)}</div>+ <RestoreOriginalsDialog+ opened={revertConfirmName !== null || revertAllTarget !== null}+ fileName={revertConfirmName ?? undefined}+ onClose={() => {+ setRevertConfirmName(null);+ setRevertAllTarget(null);+ }}+ onConfirm={() => {+ if (revertConfirmName) revertFolderFile(revertConfirmName);+ if (revertAllTarget) revertAllInFolder(revertAllTarget);+ }}+ />+ <FolderProcessingSetup+ folder={processingSetupFolder}+ onClose={() => setProcessingSetupFolder(null)}+ />+{/* Drawer hosts the details panel on ≤800px viewports. */}{isCompactDetailsViewport && (<Drawer@@ -2109,6 +2687,18 @@ export default function FileManagerView() {);}+/**+ * A cheap identity for a directory listing, so a background re-read only re-renders the+ * grid when something actually changed on disk.+ */+function listingSignature(+ files: { path: string; sizeBytes: number; lastModified: number }[],+): string {+ return files+ .map((file) => `${file.path}|${file.sizeBytes}|${file.lastModified}`)+ .join("\n");+}+function Breadcrumbs() {const { t } = useTranslation();const folders = useFolders();diff --git a/frontend/editor/src/core/components/filesPage/FilesPage.css b/frontend/editor/src/core/components/filesPage/FilesPage.cssindex 5900971bdb..5df6692b63 100644--- a/frontend/editor/src/core/components/filesPage/FilesPage.css+++ b/frontend/editor/src/core/components/filesPage/FilesPage.css@@ -530,6 +530,176 @@}}+/* Marks a folder that runs a pipeline over anything added to it. Replaces the+ item count so a processing folder reads as a different kind of thing. */+.files-page-processing-tag {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ padding: 0.05rem 0.4rem;+ border-radius: var(--radius-sm, 4px);+ font-size: 0.72rem;+ font-weight: 600;+ color: var(--c-success-text, var(--c-primary));+ background: color-mix(+ in srgb,+ var(--c-success, var(--c-primary)) 14%,+ transparent+ );+}++.files-page-processing-tag::before {+ content: "";+ width: 0.4rem;+ height: 0.4rem;+ border-radius: 50%;+ background: currentColor;+}++/* Per-file processing state on a working folder's listing. The badge names the+ state; a not-yet-processed file is also inert (no open, no menu) until its+ result exists, and reads that way. */+.files-page-state-badge {+ position: absolute;+ top: 6px;+ right: 6px;+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ padding: 0.1rem 0.4rem;+ border-radius: 999px;+ font-size: 0.68rem;+ font-weight: 600;+ background: var(--c-surface-raised);+ border: 1px solid var(--c-border-subtle);+ color: var(--c-text-muted);+}++.files-page-state-badge.is-failed {+ color: var(--c-danger, var(--c-text));+ border-color: color-mix(+ in srgb,+ var(--c-danger, var(--c-text)) 40%,+ transparent+ );+}++.files-page-state-badge.is-done {+ color: var(--c-success, var(--c-primary));+ border-color: color-mix(+ in srgb,+ var(--c-success, var(--c-primary)) 40%,+ transparent+ );+}++.files-page-card.is-locked,+.files-page-list-row.is-locked {+ opacity: 0.55;+ cursor: default;+}++.files-page-card.is-locked .files-page-card-actions {+ display: none;+}++/* The open folder's own actions, inline beside the items count. */+.files-page-folder-actions {+ display: flex;+ align-items: center;+ gap: 0.3rem;+ margin-left: 0.6rem;+ padding-left: 0.6rem;+ border-left: 1px solid var(--c-border-subtle);+}++/* State filter chips above a working folder's listing. */+.files-page-state-filters {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ padding: 0 0 0.6rem;+ flex-wrap: wrap;+}++.files-page-state-filters button {+ font: inherit;+ font-size: 0.78rem;+ font-weight: 600;+ color: var(--c-text-muted);+ background: var(--c-surface-raised);+ border: 1px solid var(--c-border-subtle);+ border-radius: 999px;+ padding: 0.15rem 0.7rem;+ cursor: pointer;+}++.files-page-state-filters button.is-active {+ color: var(--c-text);+ border-color: var(--c-primary);+ background: var(--c-primary-subtle, var(--c-surface));+}++/* Count on a filter chip ("Failed 3"). */+.files-page-state-count {+ margin-left: 0.3rem;+ font-variant-numeric: tabular-nums;+ opacity: 0.75;+}++/* Retry on a failed file's badge; must stay clickable inside an inert card. */+.files-page-state-retry {+ display: inline-flex;+ align-items: center;+ gap: 0.15rem;+ margin-left: 0.3rem;+ padding: 0;+ font: inherit;+ color: inherit;+ background: none;+ border: none;+ text-decoration: underline;+ cursor: pointer;+ pointer-events: auto;+}++/* A working folder's per-state counts, one dotted chip per non-zero state. */+.files-page-folder-stats {+ display: flex;+ flex-wrap: wrap;+ gap: 0.35rem;+ margin-top: 0.3rem;+}++.files-page-folder-stat {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ font-size: 0.7rem;+ font-weight: 600;+ color: var(--c-text-muted);+}++.files-page-folder-stat::before {+ content: "";+ width: 0.4rem;+ height: 0.4rem;+ border-radius: 50%;+ background: var(--c-border-strong);+}++.files-page-folder-stat.is-done::before {+ background: var(--c-success, var(--c-primary));+}++.files-page-folder-stat.is-processing::before {+ background: var(--c-primary);+}++.files-page-folder-stat.is-failed::before {+ background: var(--c-danger, var(--c-text));+}+/* Parent-folder breadcrumb shown on cards/rows during recursive search sothe user can tell which folder each hit lives in without navigating. */.files-page-card-path {diff --git a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsxindex 63e8cf8841..e95c0d6d50 100644--- a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx+++ b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx@@ -531,10 +531,7 @@ function TreeNodeRow({}>{kind === "local"- ? t(- "filesPage.removeLocalFolder",- "Remove (files stay on disk)",- )+ ? t("filesPage.removeLocalFolder", "Unmount from Stirling"): t("filesPage.treeMenu.delete", "Delete folder")}</Menu.Item>)}diff --git a/frontend/editor/src/core/components/filesPage/RestoreOriginalsDialog.tsx b/frontend/editor/src/core/components/filesPage/RestoreOriginalsDialog.tsxnew file mode 100644index 0000000000..aa88bd27a0--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/RestoreOriginalsDialog.tsx@@ -0,0 +1,74 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Group, Modal, Stack, Text } from "@mantine/core";+import { Button } from "@app/ui/Button";++interface RestoreOriginalsDialogProps {+ opened: boolean;+ /** The single file being restored; absent means every original in the folder. */+ fileName?: string;+ onClose: () => void;+ onConfirm: () => void | Promise<void>;+}++/**+ * Confirms a restore before it runs: bringing originals back pauses the+ * folder's processing, and the restored files read as waiting until the user+ * resumes — a state change worth saying out loud rather than springing.+ */+export function RestoreOriginalsDialog({+ opened,+ fileName,+ onClose,+ onConfirm,+}: RestoreOriginalsDialogProps) {+ const { t } = useTranslation();+ const [submitting, setSubmitting] = useState(false);+ useEffect(() => {+ if (opened) setSubmitting(false);+ }, [opened]);+ return (+ <Modal+ opened={opened}+ onClose={onClose}+ title={t("filesPage.processing.revertConfirmTitle", "Restore originals?")}+ centered+ size="md"+ >+ <Stack gap="md">+ <Text size="sm">+ {fileName+ ? t("filesPage.processing.revertConfirmFile", {+ name: fileName,+ defaultValue:+ 'Restore "{{name}}" to its original? Processing for this folder will be paused, and the file shows as queued until you resume.',+ })+ : t(+ "filesPage.processing.revertConfirmAll",+ "Restore every original in this folder? Processing will be paused, and restored files show as queued until you resume.",+ )}+ </Text>+ <Group justify="flex-end" gap="sm">+ <Button+ variant="tertiary"+ size="sm"+ onClick={onClose}+ disabled={submitting}+ >+ {t("filesPage.processing.revertCancel", "Cancel")}+ </Button>+ <Button+ size="sm"+ onClick={() => {+ setSubmitting(true);+ void Promise.resolve(onConfirm()).finally(onClose);+ }}+ loading={submitting}+ >+ {t("filesPage.processing.revertConfirm", "Restore and pause")}+ </Button>+ </Group>+ </Stack>+ </Modal>+ );+}diff --git a/frontend/editor/src/core/components/policies/DownloadsProcessingWizard.tsx b/frontend/editor/src/core/components/policies/DownloadsProcessingWizard.tsxnew file mode 100644index 0000000000..effe5fa74a--- /dev/null+++ b/frontend/editor/src/core/components/policies/DownloadsProcessingWizard.tsx@@ -0,0 +1,7 @@+/**+ * Core stub for the Downloads processing offer. The real implementation lives at the+ * same path under proprietary/ and shadows this via the @app/* alias cascade.+ */+export function DownloadsProcessingWizard(_props?: { active?: boolean }) {+ return null;+}diff --git a/frontend/editor/src/core/components/policies/FolderProcessingSetup.tsx b/frontend/editor/src/core/components/policies/FolderProcessingSetup.tsxnew file mode 100644index 0000000000..b4400b383c--- /dev/null+++ b/frontend/editor/src/core/components/policies/FolderProcessingSetup.tsx@@ -0,0 +1,15 @@+import type { FolderRecord } from "@app/types/folder";++export interface FolderProcessingSetupProps {+ /** The folder being set up; null keeps the dialog closed. */+ folder: FolderRecord | null;+ onClose: () => void;+}++/**+ * Core stub for the folder-processing setup dialog. The real implementation lives at+ * the same path under proprietary/ and shadows this via the @app/* alias cascade.+ */+export function FolderProcessingSetup(_props: FolderProcessingSetupProps) {+ return null;+}diff --git a/frontend/editor/src/core/components/policies/SweepRunWall.tsx b/frontend/editor/src/core/components/policies/SweepRunWall.tsxnew file mode 100644index 0000000000..18fb3d9de4--- /dev/null+++ b/frontend/editor/src/core/components/policies/SweepRunWall.tsx@@ -0,0 +1,13 @@+export interface FolderSweepWallProps {+ /** The processing record whose runs to watch; absent renders nothing. */+ policyId?: string;+}++/**+ * Core stub for the live sweep wall a working folder raises while its pipeline runs. The+ * real implementation lives at the same path under proprietary/ and shadows this via the+ * @app/* alias cascade.+ */+export function FolderSweepWall(_props: FolderSweepWallProps) {+ return null;+}diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsxindex 5fa5e7cb27..b01e8a4453 100644--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx@@ -57,6 +57,7 @@ import { DeleteFilesDialog } from "@app/components/filesPage/DeleteFilesDialog";import { RenameFileDialog } from "@app/components/shared/RenameFileDialog";import { duplicateStoredFile } from "@app/utils/duplicateFile";import { SidebarChecklistSlot } from "@app/components/shared/SidebarChecklistSlot";+import { SidebarProcessingSlot } from "@app/components/shared/SidebarProcessingSlot";import {deleteServerFile,type DeleteScope,@@ -1335,6 +1336,10 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>()}</div></NavSurface>++ {/* Offer to process a folder of files (e.g. Downloads), beneath the+ files section. Empty in builds without a policy engine. */}+ <SidebarProcessingSlot collapsed={collapsed} /></div>{/* Kebab "Save to cloud" upload modal (one file at a time). */}diff --git a/frontend/editor/src/core/components/shared/SidebarProcessingSlot.tsx b/frontend/editor/src/core/components/shared/SidebarProcessingSlot.tsxnew file mode 100644index 0000000000..f69ce6d6d8--- /dev/null+++ b/frontend/editor/src/core/components/shared/SidebarProcessingSlot.tsx@@ -0,0 +1,11 @@+export interface SidebarProcessingSlotProps {+ collapsed?: boolean;+}++/**+ * Extension point for a processing-folder offer in the sidebar's controls box. Core has+ * no policy engine to run one; builds that ship processing folders shadow this file.+ */+export function SidebarProcessingSlot(_props: SidebarProcessingSlotProps) {+ return null;+}diff --git a/frontend/editor/src/core/contexts/FolderContext.test.tsx b/frontend/editor/src/core/contexts/FolderContext.test.tsxindex 645f7166de..953b599cf6 100644--- a/frontend/editor/src/core/contexts/FolderContext.test.tsx+++ b/frontend/editor/src/core/contexts/FolderContext.test.tsx@@ -72,11 +72,22 @@ vi.mock("@app/auth/UseSession", () => ({// Stateful IDB mock - the revision-driven refresh re-reads getAllFolders// after every state change, so a stateless [] mock would clobber pull results.const { mockIdb } = vi.hoisted(() => ({- mockIdb: { folders: [] as { id: string }[] },+ mockIdb: {+ folders: [] as { id: string }[],+ nextReadGate: null as Promise<void> | null,+ reads: 0,+ },}));vi.mock("@app/services/folderStorage", () => ({folderStorage: {- getAllFolders: vi.fn(() => Promise.resolve([...mockIdb.folders])),+ getAllFolders: vi.fn(async () => {+ const snapshot = [...mockIdb.folders];+ const gate = mockIdb.nextReadGate;+ mockIdb.nextReadGate = null;+ mockIdb.reads += 1;+ if (gate) await gate;+ return snapshot;+ }),replaceAll: vi.fn((next: { id: string }[]) => {mockIdb.folders = [...next];return Promise.resolve();@@ -279,6 +290,8 @@ describe("FolderContext stale-folder 404 cleanup", () => {mockDelete.mockReset();// Reset the stateful IDB mock so each test starts with an empty cache.mockIdb.folders = [];+ mockIdb.nextReadGate = null;+ mockIdb.reads = 0;// Signed-in, non-anonymous user so pullFromServer runs.mockAuth.user = { id: "test-user", is_anonymous: false };mockAuth.isAnonymous = false;@@ -369,6 +382,29 @@ describe("FolderContext stale-folder 404 cleanup", () => {expect(screen.getByTestId("reachable").textContent).toBe("true");});+ test("a late initial cache read cannot replace a newer server snapshot", async () => {+ const folder = makeFolder("server folder");+ let releaseCacheRead: (() => void) | undefined;+ mockIdb.nextReadGate = new Promise<void>((resolve) => {+ releaseCacheRead = resolve;+ });++ const api = await setupWithFolders([folder]);+ await waitFor(() => expect(mockIdb.reads).toBeGreaterThanOrEqual(2));++ await act(async () => {+ releaseCacheRead?.();+ });++ expect(screen.getByTestId("count").textContent).toBe("1");+ mockUpdate.mockResolvedValueOnce({ ...folder, name: "renamed" });+ let renamed: unknown;+ await act(async () => {+ renamed = await api.current.rename(folder.id, "renamed");+ });+ expect(renamed).toMatchObject({ name: "renamed" });+ });+test("deleteFolder 404 is treated as already-deleted, returns [id], no banner", async () => {const target = makeFolder("target");const other = makeFolder("other");diff --git a/frontend/editor/src/core/contexts/FolderContext.tsx b/frontend/editor/src/core/contexts/FolderContext.tsxindex 975a65ba07..de3a28f9ca 100644--- a/frontend/editor/src/core/contexts/FolderContext.tsx+++ b/frontend/editor/src/core/contexts/FolderContext.tsx@@ -323,7 +323,10 @@ export function FolderProvider({ children }: FolderProviderProps) {};}, []);+ const serverSnapshotVersion = useRef(0);+const refresh = useCallback(async () => {+ const versionAtStart = serverSnapshotVersion.current;setLoading(true);try {// Three systems of record behind one list; kind says which rules a row follows.@@ -333,7 +336,15 @@ export function FolderProvider({ children }: FolderProviderProps) {localFolderStorage.getAllFolders(),]);if (!mountedRef.current) return;- setFolders([...server, ...virtual, ...local]);+ setFolders((current) =>+ serverSnapshotVersion.current === versionAtStart+ ? [...server, ...virtual, ...local]+ : [+ ...current.filter((folder) => folderKind(folder) === "server"),+ ...virtual,+ ...local,+ ],+ );} catch (err) {console.error("[FolderContext] cache read failed", err);if (mountedRef.current) {@@ -404,6 +415,7 @@ export function FolderProvider({ children }: FolderProviderProps) {console.warn("[FolderContext] cache replace failed", cacheErr);}if (mountedRef.current) {+ serverSnapshotVersion.current += 1;// Server-wins is for server rows: the other kinds have no server copy.setFolders((prev) => [...remote,diff --git a/frontend/editor/src/core/hooks/useProcessingFolders.ts b/frontend/editor/src/core/hooks/useProcessingFolders.tsnew file mode 100644index 0000000000..e97377213a--- /dev/null+++ b/frontend/editor/src/core/hooks/useProcessingFolders.ts@@ -0,0 +1,96 @@+import type { FolderRecord } from "@app/types/folder";++export interface ProcessingFolderState {+ /** The processing record's own id — not the folder's. */+ id: string;+ enabled: boolean;+ /** Where a disk-backed folder's results land, when the record names one. */+ outputDirectory?: string;+}++export interface ProcessingRunInfo {+ runId: string;+ /** The document being processed, when the run's source recorded a name. */+ fileName: string | null;+ currentStep: number;+ stepCount: number;+}++export interface ProcessingRecordSummary {+ id: string;+ enabled: boolean;+ steps: {+ operation: string;+ parameters: Record<string, unknown>;+ assets?: Record<string, unknown>;+ }[];+}++export interface MountedFileState {+ name: string;+ state: "done" | "processing" | "failed" | "waiting";+ hasOriginal?: boolean;+}++export interface ProcessingFoldersApi {+ /** The folder's processing state; undefined means an ordinary folder. */+ stateFor: (folder: FolderRecord) => ProcessingFolderState | undefined;+ recordFor: (folder: FolderRecord) => ProcessingRecordSummary | undefined;+ /** Server-storage folder ids whose processing is enabled, for id-only callers. */+ enabledFolderIds: ReadonlySet<string>;+ anyEnabled: boolean;+ /** The record's runs that are currently executing (or queued to). */+ listActiveRuns: (recordId: string) => Promise<ProcessingRunInfo[]>;+ listFiles: (recordId: string) => Promise<MountedFileState[]>;+ /** Retry one failed file now; other parked failures stay parked. */+ retryFile: (recordId: string, name: string) => Promise<void>;+ /** Restore a file's original: pauses the folder; the file reads as waiting. */+ revertFile: (recordId: string, name: string) => Promise<void>;+ /** Restore every archived original: pauses the folder; mid-run files are skipped. */+ revertAll: (+ folder: FolderRecord,+ ) => Promise<{ restored: number; skipped: number } | undefined>;+ /** Attach the default (classification) pipeline, or resume a paused one. */+ enable: (folder: FolderRecord) => Promise<void>;+ /** Pause processing; history stays, so resuming never re-runs finished work. */+ disable: (folder: FolderRecord) => Promise<void>;+ /** Remove the processing behaviour and its history; the folder and files stay. */+ remove: (folder: FolderRecord) => Promise<void>;+ sweep: (folder: FolderRecord) => Promise<void>;+}++const EMPTY_IDS: ReadonlySet<string> = new Set();++/**+ * One shared instance, so every caller sees a stable identity. Returning a fresh literal+ * per render makes the members unstable deps: an effect keyed on one of them re-runs every+ * render, and any state it sets re-renders, which is an unbounded loop.+ */+const INERT: ProcessingFoldersApi = {+ stateFor: () => undefined,+ recordFor: () => undefined,+ enabledFolderIds: EMPTY_IDS,+ anyEnabled: false,+ listActiveRuns: async () => [],+ listFiles: async () => [],+ retryFile: async () => {},+ revertFile: async () => {},+ revertAll: async () => undefined,+ enable: async () => {},+ disable: async () => {},+ remove: async () => {},+ sweep: async () => {},+};++/**+ * Processing folders, whatever kind of folder they watch. Inert in core; the proprietary+ * build shadows this with an implementation backed by `/api/v1/processing-folders`.+ */+export function useProcessingFolders(): ProcessingFoldersApi {+ return INERT;+}++/** Reload the shared list. No-op in core, which has no processing folders. */+export function refreshProcessingFolders(): Promise<void> {+ return Promise.resolve();+}diff --git a/frontend/editor/src/core/tests/helpers/api-stubs.ts b/frontend/editor/src/core/tests/helpers/api-stubs.tsindex fc476af535..5477422ca6 100644--- a/frontend/editor/src/core/tests/helpers/api-stubs.ts+++ b/frontend/editor/src/core/tests/helpers/api-stubs.ts@@ -274,6 +274,18 @@ export async function mockAppApis(route.fulfill({ json: [] }),);+ await page.route("**/api/v1/processing-folders", (route: Route) =>+ route.fulfill({ json: [] }),+ );++ await page.route(+ "**/api/v1/processing-folders/downloads-suggestion",+ (route: Route) =>+ route.fulfill({+ json: { directory: "", available: false, pdfCount: 0, limit: 0 },+ }),+ );+// The bell polls this on load. The hook swallows the failure, but the browser still logs the// request, which the console-hygiene guard counts.await page.route("**/api/v1/notifications*", (route: Route) =>diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.tsindex 69c03323eb..660b07c514 100644--- a/frontend/editor/src/portal/api/policies.ts+++ b/frontend/editor/src/portal/api/policies.ts@@ -14,12 +14,9 @@ import { apiClient } from "@portal/api/http";import { fromWirePolicy, toWirePolicy } from "@app/policies/codec";import { runsToActivity, runsToStats } from "@app/policies/runs";import {- policyStep,policyStepFromWire,type PolicyToolId,- type PolicyToolStep,} from "@app/policies/operations";-import type { ToolEndpoint } from "@app/types/toolApiTypes";import type { Policy } from "@portal/api/pipelines";import type {PolicyDecodedState,@@ -31,379 +28,19 @@ import type {export type { PolicyRunView, WirePolicy } from "@app/policies/types";-// Re-export the wire step type under the legacy name components depend on.-export type { WirePipelineStep as PipelineStep } from "@app/policies/types";--/* ──────────────────────────────────────────────────────────────────────── */-/* Catalogue model — portal-specific */-/* ──────────────────────────────────────────────────────────────────────── */--type PolicyStatus = "active" | "paused";--export type PolicyFieldType = "toggle" | "select" | "chips" | "text";--export interface PolicyField {- label: string;- key: string;- type: PolicyFieldType;- value: boolean | string | string[];- options?: string[];-}--export interface PolicyCategory {- id: string;- label: string;- tone: "neutral" | "blue" | "purple" | "green" | "amber" | "red";- desc: string;- providesClassification?: boolean;- comingSoon?: boolean;- requiresAiEngine?: boolean;-}--export interface PolicyConfigDef {- summary: string;- rules: string[];- scopeLabel: string;- fields: PolicyField[];- defaultOperations: PolicyToolStep[];-}--export interface PolicyState {- configured: boolean;- status: PolicyStatus;- /** A policy rather than an ordinary pipeline (see `Policy.required`). */- required: boolean;- name?: string;- icon?: string;- /** Options the wizard doesn't model, preserved so a wizard save round-trips them (see codec). */- extraOptions?: Record<string, unknown>;- sources: string[];- /** Whether the editor runs this policy per file; stored, not derived from `sources`. */- runsOnEditor?: boolean;- scopeTypes: string[];- reviewerEmail: string;- fieldValues: Record<string, boolean | string | string[]>;- outputMode?: "new_file" | "new_version";- outputName?: string;- outputNamePosition?: "prefix" | "suffix" | "auto-number";- runOn?: "upload" | "export";- maxRetries?: number;- retryDelayMinutes?: number;- backendId?: string;- isDefault?: boolean;-}--export interface PolicySetupResult {- required: boolean;- /** Stored options the wizard doesn't model, carried through so a save preserves them (see codec). */- extraOptions?: Record<string, unknown>;- fieldValues: Record<string, boolean | string | string[]>;- sources: string[];- runsOnEditor: boolean;- scopeTypes: string[];- reviewerEmail: string;- outputMode: "new_file" | "new_version";- outputName: string;- outputNamePosition: "prefix" | "suffix" | "auto-number";- runOn: "upload" | "export";- maxRetries: number;- retryDelayMinutes: number;- steps: WirePipelineStep[];-}--export interface DecoratedPolicy {- category: PolicyCategory;- config: PolicyConfigDef;- state: PolicyState;- steps: WirePipelineStep[];- stats: import("@app/policies/types").PolicyStats;- activity: import("@app/policies/types").PolicyActivityItem[];-}--export interface PoliciesResponse {- catalogue: CatalogueEntry[];-}--export interface CatalogueEntry {- category: PolicyCategory;- config: PolicyConfigDef;- policy: DecoratedPolicy | null;-}--/* ──────────────────────────────────────────────────────────────────────── */-/* Endpoint display labels */-/* ──────────────────────────────────────────────────────────────────────── */--/**- * i18n keys keyed by endpoint; labels stored steps in the detail view. Mostly- * {@link ToolEndpoint}s, plus the AI classify endpoint, which isn't part of the generated union.- */-const ENDPOINT_LABELS: Partial<- Record<ToolEndpoint | "/api/v1/ai/tools/classify-and-label", string>-> = {- "/api/v1/security/auto-redact": "portal.policies.endpoints.autoRedact",- "/api/v1/security/sanitize-pdf": "portal.policies.endpoints.sanitizePdf",- "/api/v1/security/add-watermark": "portal.policies.endpoints.addWatermark",- "/api/v1/misc/ocr-pdf": "portal.policies.endpoints.ocrPdf",- "/api/v1/misc/flatten": "portal.policies.endpoints.flatten",- "/api/v1/misc/compress-pdf": "portal.policies.endpoints.compressPdf",- "/api/v1/ai/tools/classify-and-label":- "portal.policies.endpoints.classifyAndLabel",-};--export function humanizeEndpoint(- path: string,- t: (key: string) => string,-): string {- const label = ENDPOINT_LABELS[path as ToolEndpoint];- if (label) return t(label);- const last = path.split("/").filter(Boolean).pop() ?? path;- return last- .replace(/-/g, " ")- .replace(/\b\w/g, (c) => c.toUpperCase())- .trim();-}--/* ──────────────────────────────────────────────────────────────────────── */-/* Catalogue definitions */-/* ──────────────────────────────────────────────────────────────────────── */--const DEFAULT_PII_PATTERNS: string[] = [- "\\b(?!000|666|9\\d{2})\\d{3}([- ])(?!00)\\d{2}\\1(?!0000)\\d{4}\\b",- "\\b(?:4\\d{12}(?:\\d{3})?|5[1-5]\\d{14}|3[47]\\d{13}|6(?:011|5\\d{2})\\d{12})\\b",-];--/** `label`/`desc` values are i18n keys — render with t(). */-export const POLICY_CATEGORIES: PolicyCategory[] = [- {- id: "ingestion",- label: "portal.policies.categories.ingestion.label",- tone: "blue",- desc: "portal.policies.categories.ingestion.desc",- providesClassification: true,- comingSoon: true,- },- {- id: "security",- label: "portal.policies.categories.security.label",- tone: "purple",- desc: "portal.policies.categories.security.desc",- },- {- id: "classification",- label: "portal.policies.categories.classification.label",- tone: "blue",- desc: "portal.policies.categories.classification.desc",- providesClassification: true,- },- {- id: "compliance",- label: "portal.policies.categories.compliance.label",- tone: "amber",- desc: "portal.policies.categories.compliance.desc",- comingSoon: true,- },- {- id: "routing",- label: "portal.policies.categories.routing.label",- tone: "green",- desc: "portal.policies.categories.routing.desc",- comingSoon: true,- },- {- id: "retention",- label: "portal.policies.categories.retention.label",- tone: "neutral",- desc: "portal.policies.categories.retention.desc",- comingSoon: true,- },-];--/**- * `summary`/`rules`/`scopeLabel`/field `label` values are i18n keys — render- * with t(). Field `value`/`options` strings are persisted policy state and- * stay as stable values (translating them would corrupt saved configs).- */-export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {- ingestion: {- summary: "portal.policies.config.ingestion.summary",- rules: [- "portal.policies.config.ingestion.rules.0",- "portal.policies.config.ingestion.rules.1",- "portal.policies.config.ingestion.rules.2",- "portal.policies.config.ingestion.rules.3",- ],- scopeLabel: "portal.policies.config.scopeAll",- defaultOperations: [policyStep("ocr"), policyStep("flatten")],- fields: [- {- label: "portal.policies.config.ingestion.fields.minConfidence",- key: "minConfidence",- type: "select",- value: "p80",- options: ["p60", "p70", "p80", "p90", "p95"],- },- {- label: "portal.policies.config.ingestion.fields.belowThreshold",- key: "belowThreshold",- type: "select",- value: "flagForReview",- options: ["flagForReview", "routeToBucket", "hold"],- },- ],- },- security: {- summary: "portal.policies.config.security.summary",- rules: [- "portal.policies.config.security.rules.0",- "portal.policies.config.security.rules.1",- "portal.policies.config.security.rules.2",- ],- scopeLabel: "portal.policies.config.scopeAll",- defaultOperations: [- // Flatten to image so redactions can't be lifted off.- policyStep("redact", {- useRegex: true,- convertPDFToImage: true,- wordsToRedact: DEFAULT_PII_PATTERNS,- }),- // JavaScript removal only; the tool enables removeEmbeddedFiles by default, so turn it off.- policyStep("sanitize", { removeEmbeddedFiles: false }),- // Bake in via image so it can't be stripped.- policyStep("watermark", { convertPDFToImage: true }),- ],- fields: [],- },- classification: {- summary: "portal.policies.config.classification.summary",- rules: [- "portal.policies.config.classification.rules.0",- "portal.policies.config.classification.rules.1",- ],- scopeLabel: "portal.policies.config.scopeAll",- defaultOperations: [policyStep("classify")],- fields: [],- },- compliance: {- summary: "portal.policies.config.compliance.summary",- rules: [- "portal.policies.config.compliance.rules.0",- "portal.policies.config.compliance.rules.1",- "portal.policies.config.compliance.rules.2",- ],- scopeLabel: "portal.policies.config.scopeAll",- // Apply writes our sensitivity label into the document after it is sanitised and flattened.- // Offered only once a Purview tenant is connected (it needs a tenant connection and a label- // GUID, which no default can guess), and hidden entirely until then.- defaultOperations: [- policyStep("sanitize"),- policyStep("flatten"),- policyStep("purviewApplyLabel"),- ],- fields: [- {- label: "portal.policies.config.compliance.fields.frameworks",- key: "frameworks",- type: "chips",- value: ["hipaa"],- options: ["hipaa", "gdpr", "soc2", "fedramp", "pciDss", "iso27001"],- },- {- label: "portal.policies.config.compliance.fields.onViolation",- key: "onViolation",- type: "select",- value: "flagForReview",- options: [- "flagForReview",- "blockExport",- "autoRedactPhi",- "quarantineDocument",- ],- },- {- label: "portal.policies.config.compliance.fields.auditTrail",- key: "auditTrail",- type: "toggle",- value: true,- },- {- label: "portal.policies.config.compliance.fields.accessLog",- key: "accessLog",- type: "toggle",- value: true,- },- ],- },- routing: {- summary: "portal.policies.config.routing.summary",- rules: [- "portal.policies.config.routing.rules.0",- "portal.policies.config.routing.rules.1",- "portal.policies.config.routing.rules.2",- ],- scopeLabel: "portal.policies.config.scopeAll",- defaultOperations: [policyStep("compress")],- fields: [- {- label: "portal.policies.config.routing.fields.destination",- key: "destination",- type: "select",- value: "documents",- options: ["documents", "s3Bucket", "sharePoint", "webhook"],- },- {- label: "portal.policies.config.routing.fields.webhookUrl",- key: "webhookUrl",- type: "text",- value: "",- },- {- label: "portal.policies.config.routing.fields.notify",- key: "notify",- type: "toggle",- value: false,- },- ],- },- retention: {- summary: "portal.policies.config.retention.summary",- rules: [- "portal.policies.config.retention.rules.0",- "portal.policies.config.retention.rules.1",- "portal.policies.config.retention.rules.2",- ],- scopeLabel: "portal.policies.config.scopeAll",- defaultOperations: [policyStep("compress")],- fields: [- {- label: "portal.policies.config.retention.fields.keepFor",- key: "keepFor",- type: "select",- value: "sevenYears",- options: [- "thirtyDays",- "oneYear",- "threeYears",- "sevenYears",- "indefinite",- ],- },- {- label: "portal.policies.config.retention.fields.archiveAfter",- key: "archiveAfter",- type: "select",- value: "never",- options: ["thirtyDays", "ninetyDays", "oneYear", "never"],- },- {- label: "portal.policies.config.retention.fields.immutableHold",- key: "immutableHold",- type: "toggle",- value: false,- },- ],- },-};+/* Catalogue model + definitions live in @app/policies/catalog - shared with the+ editor's folder-processing setup - and are re-exported here for the portal. */+export * from "@app/policies/catalog";+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 ───────────────────────────────────────────diff --git a/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsx b/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsxindex 197c863e70..950ba6b749 100644--- a/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsx+++ b/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsx@@ -1,50 +1,3 @@-import { useTranslation } from "react-i18next";-import { InfoTooltip, ToggleSwitch } from "@app/ui";-import "@portal/components/pipelines/EnforceAsPolicyControl.css";--export interface EnforceAsPolicyControlProps {- /** Org-mandated policy (see Policy.required). */- required: boolean;- onRequiredChange: (required: boolean) => void;- /** Lock the toggle for a non-manager. */- disabled?: boolean;- /**- * The permission check is still loading. The toggle stays locked, but the manager-only tooltip is- * withheld so a still-loading manager isn't told they lack permission.- */- permissionsLoading?: boolean;-}--/**- * The "Enforce as policy" switch plus the app's standard inline (i) info affordance explaining what- * it means. Shared by the builder header and the simple wizard so the control reads and behaves- * identically wherever a pipeline can be made org-mandated.- */-export function EnforceAsPolicyControl({- required,- onRequiredChange,- disabled = false,- permissionsLoading = false,-}: EnforceAsPolicyControlProps) {- const { t } = useTranslation();- return (- <span className="portal-enforce">- <ToggleSwitch- size="sm"- checked={required}- onChange={onRequiredChange}- disabled={disabled}- label={t("portal.pipelines.enforce.label")}- />- <InfoTooltip- label={- disabled && !permissionsLoading- ? t("portal.pipelines.enforce.managerOnly")- : t("portal.pipelines.enforce.desc")- }- ariaLabel={t("portal.pipelines.enforce.info")}- position="bottom"- />- </span>- );-}+/* Lives in the shared policies layer so the editor's folder-processing setup renders+ the same wizard. */+export { EnforceAsPolicyControl } from "@app/components/policies/EnforceAsPolicyControl";diff --git a/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.tsx b/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.tsxindex 742247a9db..6c08dd807e 100644--- a/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.tsx+++ b/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.tsx@@ -1,57 +1 @@-import { useTranslation } from "react-i18next";-import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded";-import LockOutlinedIcon from "@mui/icons-material/LockOutlined";-import { OptionCard } from "@app/ui";-import type { CatalogueEntry } from "@portal/api/policies";-import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";--interface PipelineTemplateCardProps {- entry: CatalogueEntry;- /** Open the simple setup wizard seeded from this template. */- onOpen: (entry: CatalogueEntry) => void;- /** Setup is unavailable (e.g. the AI engine is off): shown, but not openable. */- locked?: boolean;- /** Chip text explaining why setup is locked (e.g. "Requires AI engine"). */- lockedLabel?: string;-}--/**- * A template in the Pipelines gallery: a ready-made starting point that opens the simple, guided- * setup. A thin adapter over the {@link OptionCard} primitive - it maps the catalogue category to- * the card's icon/title/blurb and picks the CTA vs the disabled note (coming soon / AI-locked).- */-export function PipelineTemplateCard({- entry,- onOpen,- locked = false,- lockedLabel,-}: PipelineTemplateCardProps) {- const { t } = useTranslation();- const { category } = entry;- const comingSoon = category.comingSoon === true;- const disabled = comingSoon || locked;-- return (- <OptionCard- icon={policyCategoryIcon(category.id)}- title={t(category.label)}- description={t(category.desc)}- disabled={disabled}- onSelect={() => onOpen(entry)}- cta={- <>- {t("portal.pipelines.templates.setUp")}- <ArrowForwardRoundedIcon style={{ fontSize: "1rem" }} />- </>- }- note={- <>- <LockOutlinedIcon style={{ fontSize: "0.95rem" }} />- {comingSoon- ? t("portal.policies.card.comingSoon")- : (lockedLabel ?? t("portal.policies.card.requiresAiEngine"))}- </>- }- />- );-}+export { PipelineTemplateCard } from "@app/components/policies/PipelineTemplateCard";diff --git a/frontend/editor/src/portal/components/policies/ClassificationLabelsSection.tsx b/frontend/editor/src/portal/components/policies/ClassificationLabelsSection.tsxindex 4b3fae7652..03e5ad04d4 100644--- a/frontend/editor/src/portal/components/policies/ClassificationLabelsSection.tsx+++ b/frontend/editor/src/portal/components/policies/ClassificationLabelsSection.tsx@@ -1,97 +1 @@-// Read-only view of the classification vocabulary shown in the policy wizard. The labels and their-// categories are a fixed, built-in set shared across the whole team — there's nothing to edit, but-// the full vocabulary is browsable: expand a category to see the labels it groups.--import { useState } from "react";-import { useTranslation } from "react-i18next";-import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";-import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";-import { Button, Card, Chip } from "@app/ui";-import { LocalIcon } from "@app/components/shared/LocalIcon";-import {- DEFAULT_CLASSIFICATION_LABELS,- LABEL_FAMILIES,-} from "@app/data/classificationLabels";-import "@portal/components/policies/ClassificationLabelsSection.css";--export function ClassificationLabelsSection() {- const { t } = useTranslation();- const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());-- const toggle = (id: string) =>- setExpanded((prev) => {- const next = new Set(prev);- if (next.has(id)) next.delete(id);- else next.add(id);- return next;- });-- return (- <Card>- <div className="classification-summary">- <div className="classification-summary-stats">- <span>- <strong>{DEFAULT_CLASSIFICATION_LABELS.length}</strong>{" "}- {t("policies.labels.labelCount", "labels")}- </span>- <span>- <strong>{LABEL_FAMILIES.length}</strong>{" "}- {t("policies.labels.categoryCount", "categories")}- </span>- </div>-- <ul className="classification-categories">- {LABEL_FAMILIES.map((family) => {- const open = expanded.has(family.id);- return (- <li key={family.id} className="classification-category">- <Button- variant="quiet"- fullWidth- justify="between"- className="classification-category-header"- aria-expanded={open}- onClick={() => toggle(family.id)}- leftSection={- <span className="classification-category-lead">- {open ? (- <KeyboardArrowDownIcon sx={{ fontSize: "1.1rem" }} />- ) : (- <KeyboardArrowRightIcon sx={{ fontSize: "1.1rem" }} />- )}- <LocalIcon icon={family.icon} width="1.1rem" />- <span className="classification-category-name">- {t(`classification.families.${family.id}`, family.name)}- </span>- </span>- }- rightSection={- <span className="classification-category-count">- {family.labels.length}- </span>- }- />- {open && (- <div className="classification-category-labels">- {family.labels.map((label) => (- <Chip key={label.id} accent="neutral" size="sm">- {t(`classification.labels.${label.id}`, label.name)}- </Chip>- ))}- </div>- )}- </li>- );- })}- </ul>-- <span className="classification-summary-note">- {t(- "policies.labels.sharedNote",- "These labels are built in and shared across your whole team.",- )}- </span>- </div>- </Card>- );-}+export * from "@app/components/policies/ClassificationLabelsSection";diff --git a/frontend/editor/src/portal/components/policies/PolicyCategoryIcon.tsx b/frontend/editor/src/portal/components/policies/PolicyCategoryIcon.tsxindex 89243711c9..75ed3028fd 100644--- a/frontend/editor/src/portal/components/policies/PolicyCategoryIcon.tsx+++ b/frontend/editor/src/portal/components/policies/PolicyCategoryIcon.tsx@@ -1,16 +1,3 @@-import type { PolicyCategory } from "@portal/api/policies";-import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";-import "@portal/components/policies/PolicyCategoryIcon.css";--/** A neutral gray rounded badge holding the category's shared outline icon. */-export function PolicyCategoryBadge({- category,-}: {- category: PolicyCategory;-}) {- return (- <span className="pcat-badge" aria-hidden>- {policyCategoryIcon(category.id)}- </span>- );-}+/* Shared as PolicyCategoryBadge: the name sidesteps a case-insensitive clash with+ policyCategoryIcon.tsx, which is why this path's export is named differently. */+export * from "@app/components/policies/PolicyCategoryBadge";diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsxindex 0986148cfa..5cab1d870b 100644--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx@@ -1,36 +1,17 @@-import { useMemo, useState } from "react";-import { useTranslation } from "react-i18next";-import TuneRoundedIcon from "@mui/icons-material/TuneRounded";-import { Banner, Button, Card, Modal, ToggleSwitch } from "@app/ui";-import { SettingsRow } from "@app/ui/SettingsRow";-import { EnforceAsPolicyControl } from "@portal/components/pipelines/EnforceAsPolicyControl";-import {- humanizeEndpoint,- type CatalogueEntry,- type PipelineStep,- type PolicySetupResult,-} from "@portal/api/policies";-import {- policyEndpoint,- policyStepFromWire,- policyStepToWire,- type PolicyParams,- type PolicyToolId,- type PolicyToolStep,-} from "@app/policies/operations";-import { resolveRunOn } from "@app/policies/runOn";+/**+ * Portal lens on the shared setup wizard: supplies the portal-only seams, the integrations+ * lookup that gates Purview steps, the Purview inline config and the portal's error copy.+ */++import { PolicySetupWizard as SharedPolicySetupWizard } from "@app/components/policies/PolicySetupWizard";+import type { CatalogueEntry, PolicySetupResult } from "@portal/api/policies";import { fetchIntegrations } from "@portal/api/integrations";import { errorMessage } from "@portal/api/http";import { useAsync } from "@portal/hooks/useAsync";-import { PolicyCategoryBadge } from "@portal/components/policies/PolicyCategoryIcon";-import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";-import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";+import { useMemo } from "react";import { PolicyPurviewConfig } from "@portal/components/policies/PolicyPurviewConfig";-import { ClassificationLabelsSection } from "@portal/components/policies/ClassificationLabelsSection";-import "@portal/views/Policies.css";interface PolicySetupWizardProps {- /** The category being configured, or null when closed. */entry: CatalogueEntry | null;/** Whether the user may edit pipelines and policies (a manager); when false the wizard is read-only. */canManagePolicies?: boolean;@@ -40,248 +21,11 @@ interface PolicySetupWizardProps {*/permissionsLoading?: boolean;onClose: () => void;- /**- * Fires on submit with the collected settings + built pipeline steps. May be- * async; if it rejects the wizard re-enables submit and surfaces the failure.- */onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;- /**- * Fires when the user asks to Customise: hands the current (unsaved) settings to the full pipeline- * builder, which takes over editing. The builder can express anything the simple wizard can't, so- * this is a one-way step unless the pipeline stays simple-representable.- */onCustomise: (entry: CatalogueEntry, result: PolicySetupResult) => void;}-/** A policy step plus whether it runs. */-type ToolState = PolicyToolStep & { enabled: boolean };--/** Resolve each field's effective value: saved override, else definition default. */-function resolveFieldValues(- entry: CatalogueEntry,-): Record<string, boolean | string | string[]> {- const saved = entry.policy?.state.fieldValues ?? {};- const out: Record<string, boolean | string | string[]> = {};- for (const f of entry.config.fields) out[f.key] = saved[f.key] ?? f.value;- return out;-}--/**- * Seed the workflow's tools. A configured policy's saved steps win (so editing- * round-trips); otherwise the category preset's default chain. Each preset step- * starts enabled — the user toggles tools off in the workflow.- */-// Temporary until the catalogue carries a defaultEnabled flag.-// Steps that cannot work until someone configures them, so they start off rather than failing-// every run of a freshly created policy. Purview needs a tenant connection and a label GUID.-const DISABLED_BY_DEFAULT = new Set<PolicyToolId>([- "watermark",- "purviewApplyLabel",- "purviewReadLabel",- "externalApiCall",-]);--// Steps that cannot work without a Purview tenant connection, so they are hidden entirely until one-// is configured rather than offered as an option that can only fail.-const PURVIEW_TOOLS = new Set<PolicyToolId>([- "purviewApplyLabel",- "purviewReadLabel",-]);--/**- * Policy-facing framing for each capability a policy can include. Labels and- * descriptions describe what the policy DOES to a document — deliberately not- * naming the underlying tool — so the setup reads as the policy's own settings- * rather than an assembled chain of tools. Endpoints with no entry fall back to- * the humanised endpoint name with no description.- */-const CAPABILITY_META: Record<- PolicyToolId,- { labelKey: string; labelEn: string; descKey: string; descEn: string }-> = {- redact: {- labelKey: "portal.policies.wizard.capability.redact.label",- labelEn: "Redact sensitive information",- descKey: "portal.policies.wizard.capability.redact.desc",- descEn:- "Finds and blacks out sensitive details — like Social Security and card numbers — so they can't be read.",- },- sanitize: {- labelKey: "portal.policies.wizard.capability.sanitize.label",- labelEn: "Strip active content",- descKey: "portal.policies.wizard.capability.sanitize.desc",- descEn:- "Removes hidden JavaScript so nothing can run automatically when the document is opened.",- },-- timestampPdf: {- labelKey: "portal.policies.wizard.capability.timestampPdf.label",- labelEn: "Add a trusted timestamp",- descKey: "portal.policies.wizard.capability.timestampPdf.desc",- descEn:- "Proves the document existed in this exact form at a point in time, using an independent timestamp authority. Only a hash is sent - the document never leaves your server.",- },- watermark: {- labelKey: "portal.policies.wizard.capability.watermark.label",- labelEn: "Apply a watermark",- descKey: "portal.policies.wizard.capability.watermark.desc",- descEn: "Stamps a visible mark (e.g. “Confidential”) across every page.",- },- ocr: {- labelKey: "portal.policies.wizard.capability.ocr.label",- labelEn: "Make text searchable",- descKey: "portal.policies.wizard.capability.ocr.desc",- descEn: "Runs OCR so scanned pages become selectable, searchable text.",- },- flatten: {- labelKey: "portal.policies.wizard.capability.flatten.label",- labelEn: "Flatten the document",- descKey: "portal.policies.wizard.capability.flatten.desc",- descEn:- "Merges form fields and annotations into the page so they can't be edited.",- },- compress: {- labelKey: "portal.policies.wizard.capability.compress.label",- labelEn: "Reduce file size",- descKey: "portal.policies.wizard.capability.compress.desc",- descEn: "Compresses the document to a smaller file size.",- },- classify: {- labelKey: "portal.policies.wizard.capability.classify.label",- labelEn: "Classify the document",- descKey: "portal.policies.wizard.capability.classify.desc",- descEn:- "Identifies the document's type from your team's labels and tags it, so it files and searches by category.",- },- purviewApplyLabel: {- labelKey: "portal.policies.wizard.capability.purviewApplyLabel.label",- labelEn: "Apply a Microsoft Purview sensitivity label",- descKey: "portal.policies.wizard.capability.purviewApplyLabel.desc",- descEn:- "Marks the document with one of your organisation's Purview labels, so Purview-aware tools recognise how sensitive it is.",- },- purviewReadLabel: {- labelKey: "portal.policies.wizard.capability.purviewReadLabel.label",- labelEn: "Read the document's Purview label",- descKey: "portal.policies.wizard.capability.purviewReadLabel.desc",- descEn:- "Reports the Purview label a document already carries, so the rest of the policy can act on how sensitive it is.",- },- externalApiCall: {- labelKey: "portal.policies.wizard.capability.externalApiCall.label",- labelEn: "Send the document to another system",- descKey: "portal.policies.wizard.capability.externalApiCall.desc",- descEn:- "Hands the document to a system you have connected, and records what it answered.",- },-};--function seedTools(entry: CatalogueEntry): ToolState[] {- const savedSteps = entry.policy?.steps ?? [];- const savedByTool = new Map<PolicyToolId, PolicyToolStep>();- for (const wire of savedSteps) {- const step = policyStepFromWire(wire);- if (step) savedByTool.set(step.toolId, step);- }- // defaultOperations is the canonical list (so tools added later still show on edit); a saved- // step's params win over the preset.- return entry.config.defaultOperations.map((preset) => {- const saved = savedByTool.get(preset.toolId);- return {- ...(saved ?? preset),- enabled: saved- ? true- : savedSteps.length > 0- ? false- : !DISABLED_BY_DEFAULT.has(preset.toolId),- };- });-}--/**- * The real "set up a policy" flow, mirroring the editor wizard: a Workflow step- * (the tool chain — toggle which tools run) and a Settings step (policy fields,- * sources, scope, reviewer, output/run). Submitting builds the pipeline steps- * (each `operation` an endpoint path) and persists via the real POST.- */-export function PolicySetupWizard({- entry,- canManagePolicies = true,- permissionsLoading = false,- onClose,- onSubmit,- onCustomise,-}: PolicySetupWizardProps) {- // Re-key the wizard on the opened category so all state resets cleanly when a- // different category is opened (avoids stale field values bleeding across).- return entry ? (- <PolicySetupWizardBody- key={entry.category.id}- entry={entry}- canManagePolicies={canManagePolicies}- permissionsLoading={permissionsLoading}- onClose={onClose}- onSubmit={onSubmit}- onCustomise={onCustomise}- />- ) : null;-}--function PolicySetupWizardBody({- entry,- canManagePolicies,- permissionsLoading,- onClose,- onSubmit,- onCustomise,-}: {- entry: CatalogueEntry;- canManagePolicies: boolean;- permissionsLoading: boolean;- onClose: () => void;- onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;- onCustomise: (entry: CatalogueEntry, result: PolicySetupResult) => void;-}) {- const { t } = useTranslation();-- const { category, config, policy } = entry;- const isEdit = policy != null;- const isClassification = category.id === "classification";-- const [tools, setTools] = useState<ToolState[]>(() => {- const seeded = seedTools(entry);- // Classification's single tool has no toggle in the workflow step, so keep it- // enabled unconditionally — otherwise editing a policy whose saved steps- // somehow lack it would strand submit with no way to re-enable it.- return isClassification- ? seeded.map((t) => ({ ...t, enabled: true }))- : seeded;- });- // No UI for any of these: each carries the stored value through on edit, and a sensible default for- // a new policy - runOn per category (security enforces on export), the rest run-once/new-version.- 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);- // A template is a policy by nature - a failure should block the file, not wave it through - so a- // new one defaults to required (blocking). Editing preserves whatever was saved.- const [required, setRequired] = useState(policy?.state.required ?? true);- const readOnly = !canManagePolicies;-- const [submitting, setSubmitting] = useState(false);- const [error, setError] = useState<string | null>(null);-+export function PolicySetupWizard(props: PolicySetupWizardProps) {const integrationsAsync = useAsync(() => fetchIntegrations(), []);const hasPurviewConnection = useMemo(() =>@@ -290,246 +34,14 @@ function PolicySetupWizardBody({),[integrationsAsync.data],);-- // Purview steps only appear once a tenant is connected. An already-enabled one (a saved policy,- // or a tenant connected earlier) stays visible so editing a policy never silently drops it.- const visibleTools = useMemo(- () =>- tools.filter(- (tl) =>- !PURVIEW_TOOLS.has(tl.toolId) || hasPurviewConnection || tl.enabled,- ),- [tools, hasPurviewConnection],- );-- // Derive from the visible list: a hidden step is never submitted (hidden implies disabled).- const enabledTools = useMemo(- () => visibleTools.filter((tl) => tl.enabled),- [visibleTools],- );-- function setToolEnabled(toolId: PolicyToolId, enabled: boolean) {- setTools((prev) =>- prev.map((tl) => (tl.toolId === toolId ? { ...tl, enabled } : tl)),- );- }-- function setToolParams<Id extends PolicyToolId>(- toolId: Id,- params: PolicyParams<Id>,- ) {- setTools((prev) =>- prev.map((tl) =>- tl.toolId === toolId ? ({ ...tl, params } as ToolState) : tl,- ),- );- }-- /** The wizard's current state as a submit result: shared by Save and Customise. */- function collectResult(): PolicySetupResult {- const steps: PipelineStep[] = enabledTools.map((tl) =>- policyStepToWire(tl),- );- return {- required,- // Preserve any stored options this wizard has no UI for (a customised policy's sources, an- // editor-authored automation blob) rather than wiping them on save; the builder is where- // those are actually edited.- extraOptions: policy?.state.extraOptions,- runsOnEditor: true,- fieldValues,- sources: policy?.state.sources ?? [],- scopeTypes,- reviewerEmail,- outputMode,- outputName: outputName.trim(),- outputNamePosition,- runOn,- maxRetries,- retryDelayMinutes,- steps,- };- }-- // Hand the current settings to the full builder. No "needs at least one tool" guard here: the- // builder has its own, and the point of customising is to keep shaping the chain.- function customise() {- onCustomise(entry, collectResult());- }-- async function submit() {- if (submitting) return;- if (enabledTools.length === 0) {- setError(t("portal.policies.wizard.errors.noTools"));- return;- }- setError(null);- setSubmitting(true);- try {- await onSubmit(entry, collectResult());- } catch (e) {- setSubmitting(false);- // Surface the backend's actual reason (e.g. a step missing its account) rather than a- // generic failure the operator cannot act on.- setError(- errorMessage(e) || t("portal.policies.wizard.errors.saveFailed"),- );- }- }-return (- <Modal- open- onClose={onClose}- width="lg"- title={- <span className="portal-policies__wizard-title">- <PolicyCategoryBadge category={category} />- {isEdit- ? t("portal.policies.wizard.title.edit", {- category: t(category.label),- })- : t("portal.policies.wizard.title.setUp", {- category: t(category.label),- })}- </span>- }- subtitle={t(config.summary)}- footer={- <div className="portal-policies__wizard-foot">- <Button variant="tertiary" size="sm" onClick={onClose}>- {t("portal.policies.wizard.actions.cancel")}- </Button>- <Button- variant="tertiary"- size="sm"- onClick={customise}- leftSection={<TuneRoundedIcon style={{ fontSize: "1.05rem" }} />}- >- {t("portal.policies.wizard.actions.customise")}- </Button>- <Button- size="sm"- style={{ marginLeft: "auto" }}- onClick={submit}- loading={submitting}- disabled={readOnly}- >- {isEdit- ? t("portal.policies.wizard.actions.saveChanges")- : t("portal.policies.wizard.actions.enablePolicy")}- </Button>- </div>- }- >- {error && (- <Banner- tone="danger"- description={error}- className="portal-policies__wizard-banner"- />+ <SharedPolicySetupWizard+ {...props}+ hasPurviewConnection={hasPurviewConnection}+ formatError={errorMessage}+ purviewConfig={({ parameters, onChange }) => (+ <PolicyPurviewConfig parameters={parameters} onChange={onChange} />)}-- {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>- <h3 className="portal-policies__wizard-heading">- {t(- "portal.policies.wizard.classification.labelsHeading",- "Classification labels",- )}- </h3>- <ClassificationLabelsSection />- </div>- )}-- {!isClassification && (- <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>- <Card padding="none">- <div className="portal-policies__capabilities">- {visibleTools.map((tl) => {- const meta = CAPABILITY_META[tl.toolId];- const label = meta- ? t(meta.labelKey, meta.labelEn)- : humanizeEndpoint(policyEndpoint(tl.toolId), t);- const description = meta- ? t(meta.descKey, meta.descEn)- : undefined;- return (- <div- key={tl.toolId}- className="portal-policies__capability"- data-on={tl.enabled || undefined}- >- <SettingsRow- label={label}- description={description}- control={- <ToggleSwitch- size="sm"- checked={tl.enabled}- onChange={(checked) =>- setToolEnabled(tl.toolId, checked)- }- label=""- />- }- />- {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 === "purviewApplyLabel" && (- <PolicyPurviewConfig- parameters={tl.params}- onChange={(params) =>- setToolParams("purviewApplyLabel", params)- }- />- )}- </div>- )}- </div>- );- })}- </div>- </Card>- </div>- )}-- <div className="portal-policies__wizard-enforce">- <EnforceAsPolicyControl- required={required}- onRequiredChange={setRequired}- disabled={!canManagePolicies}- permissionsLoading={permissionsLoading}- />- </div>- </Modal>+ />);}diff --git a/frontend/editor/src/proprietary/components/policies/ClassificationLabelsSection.css b/frontend/editor/src/proprietary/components/policies/ClassificationLabelsSection.cssnew file mode 100644index 0000000000..13c1f4812f--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/ClassificationLabelsSection.css@@ -0,0 +1,53 @@+/* Read-only classification-vocabulary viewer in the policy wizard. */+.classification-summary {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+}+.classification-summary-stats {+ display: flex;+ gap: var(--space-3);+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}+.classification-summary-note {+ font-size: 0.75rem;+ color: var(--c-text-subtle);+}++/* Expandable category → labels list. */+.classification-categories {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+}+.classification-category {+ border-top: 1px solid var(--c-border);+}+.classification-category:last-child {+ border-bottom: 1px solid var(--c-border);+}+.classification-category-header {+ min-height: 2.5rem;+}+.classification-category-lead {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+}+.classification-category-name {+ font-weight: 600;+ font-size: 0.875rem;+}+.classification-category-count {+ font-size: 0.75rem;+ color: var(--c-text-subtle);+}+.classification-category-labels {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-1_5);+ padding: 0 var(--space-2) var(--space-2) 2rem;+}diff --git a/frontend/editor/src/proprietary/components/policies/ClassificationLabelsSection.tsx b/frontend/editor/src/proprietary/components/policies/ClassificationLabelsSection.tsxnew file mode 100644index 0000000000..0b89566c62--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/ClassificationLabelsSection.tsx@@ -0,0 +1,96 @@+// Read-only view of the classification vocabulary shown in the policy wizard: a fixed, built-in+// set shared across the whole team, browsable by expanding a category.++import { useState } from "react";+import { useTranslation } from "react-i18next";+import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";+import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";+import { Button, Card, Chip } from "@app/ui";+import { LocalIcon } from "@app/components/shared/LocalIcon";+import {+ DEFAULT_CLASSIFICATION_LABELS,+ LABEL_FAMILIES,+} from "@app/data/classificationLabels";+import "@app/components/policies/ClassificationLabelsSection.css";++export function ClassificationLabelsSection() {+ const { t } = useTranslation();+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());++ const toggle = (id: string) =>+ setExpanded((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });++ return (+ <Card>+ <div className="classification-summary">+ <div className="classification-summary-stats">+ <span>+ <strong>{DEFAULT_CLASSIFICATION_LABELS.length}</strong>{" "}+ {t("policies.labels.labelCount", "labels")}+ </span>+ <span>+ <strong>{LABEL_FAMILIES.length}</strong>{" "}+ {t("policies.labels.categoryCount", "categories")}+ </span>+ </div>++ <ul className="classification-categories">+ {LABEL_FAMILIES.map((family) => {+ const open = expanded.has(family.id);+ return (+ <li key={family.id} className="classification-category">+ <Button+ variant="quiet"+ fullWidth+ justify="between"+ className="classification-category-header"+ aria-expanded={open}+ onClick={() => toggle(family.id)}+ leftSection={+ <span className="classification-category-lead">+ {open ? (+ <KeyboardArrowDownIcon sx={{ fontSize: "1.1rem" }} />+ ) : (+ <KeyboardArrowRightIcon sx={{ fontSize: "1.1rem" }} />+ )}+ <LocalIcon icon={family.icon} width="1.1rem" />+ <span className="classification-category-name">+ {t(`classification.families.${family.id}`, family.name)}+ </span>+ </span>+ }+ rightSection={+ <span className="classification-category-count">+ {family.labels.length}+ </span>+ }+ />+ {open && (+ <div className="classification-category-labels">+ {family.labels.map((label) => (+ <Chip key={label.id} accent="neutral" size="sm">+ {t(`classification.labels.${label.id}`, label.name)}+ </Chip>+ ))}+ </div>+ )}+ </li>+ );+ })}+ </ul>++ <span className="classification-summary-note">+ {t(+ "policies.labels.sharedNote",+ "These labels are built in and shared across your whole team.",+ )}+ </span>+ </div>+ </Card>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.css b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.cssnew file mode 100644index 0000000000..d2897a72b4--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.css@@ -0,0 +1,96 @@+.downloads-wizard__title {+ display: inline-flex;+ align-items: center;+ gap: 0.45rem;+}++.downloads-wizard__body {+ display: flex;+ flex-direction: column;+ gap: 0.7rem;+ font-size: 0.9rem;+ color: var(--c-text);+}++.downloads-wizard__path {+ font-family: var(--font-mono, monospace);+ font-size: 0.8rem;+ color: var(--c-text-muted);+ background: var(--c-surface);+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-sm, 4px);+ padding: 0.35rem 0.5rem;+ word-break: break-all;+}++.downloads-wizard__facts {+ margin: 0;+ padding-left: 1.1rem;+ display: flex;+ flex-direction: column;+ gap: 0.35rem;+ font-size: 0.84rem;+ color: var(--c-text-muted);+}++.downloads-wizard__progress {+ align-items: center;+ text-align: center;+}++/* Fills as runs settle; width is driven inline from the settled/total ratio. */+.downloads-wizard__bar {+ width: 100%;+ height: 0.35rem;+ border-radius: 999px;+ background: var(--c-border-subtle);+ overflow: hidden;+}++.downloads-wizard__bar > span {+ display: block;+ height: 100%;+ border-radius: 999px;+ background: var(--c-primary);+ transition: width 0.3s ease;+}++.downloads-wizard__tick {+ color: var(--c-success, var(--c-primary));+}++.downloads-wizard__warn {+ color: var(--c-danger-text, var(--c-text));+ font-size: 0.84rem;+}++.downloads-wizard__foot {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 0.5rem;+}++/* The entry point: a compact row in the side panel holding the button that opens the offer. */+.downloads-wizard__trigger {+ display: flex;+ padding: 0.5rem;+}++.downloads-wizard__trigger > * {+ width: 100%;+ justify-content: flex-start;+}++/* ---- The card wall: every file in the sweep, lighting up as its run settles. ---- */++/* Counts header above the wall ("12 of 100 · 4 types found"). */+.downloads-wizard__counts {+ font-size: 0.82rem;+ color: var(--c-text-muted);+}++.downloads-wizard__counts strong {+ color: var(--c-text);+ font-variant-numeric: tabular-nums;+}diff --git a/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsxnew file mode 100644index 0000000000..0964a19179--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx@@ -0,0 +1,449 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Loader } from "@mantine/core";+import CheckCircleIcon from "@mui/icons-material/CheckCircle";+import FolderSpecialIcon from "@mui/icons-material/FolderSpecial";+import { Button } from "@app/ui/Button";+import { Modal } from "@app/ui/Modal";+import {+ CLASSIFY_OPERATION,+ cancelProcessingRuns,+ fetchDownloadsSuggestion,+ fetchProcessingFolders,+ fetchMountedFiles,+ saveProcessingFolder,+ type DownloadsSuggestion,+} from "@app/services/processingFolderApi";+import {+ currentRunIds,+ deliverSweepResults,+} from "@app/services/processingRunDelivery";+import {+ mergeRunsIntoCards,+ SweepRunWall,+ type SweepWallCard,+} from "@app/components/policies/SweepRunWall";+import { refreshProcessingFolders } from "@app/hooks/useProcessingFolders";+import { readClassificationLabelsFromFile } from "@app/services/fileClassification";+import { useFileHandler } from "@app/hooks/useFileHandler";+import { useFolders } from "@app/contexts/FolderContext";+import { canListDirectory } from "@app/services/localFolderContents";+import apiClient from "@app/services/apiClient";+import "@app/components/policies/DownloadsProcessingWizard.css";++type Phase = "asking" | "working" | "done" | "failed";++interface DownloadsProcessingWizardProps {+ /** Renders nothing until true, so the offer never competes with a first load. */+ active?: boolean;+}++/**+ * Offers to process the PDFs already in the user's Downloads folder, then shows what it is+ * doing: the server names its own Downloads directory and counts what waits, and approving+ * composes a processing folder over it. While the sweep runs the dialog is a wall of cards+ * built from the runs feed itself, so it never promises a file the sweep skipped.+ */+export function DownloadsProcessingWizard({+ active = true,+}: DownloadsProcessingWizardProps) {+ const { t } = useTranslation();+ const [suggestion, setSuggestion] = useState<DownloadsSuggestion | null>(+ null,+ );+ const [open, setOpen] = useState(false);+ const [phase, setPhase] = useState<Phase>("asking");+ const [processed, setProcessed] = useState(0);+ const [failed, setFailed] = useState(0);+ const [error, setError] = useState<string | null>(null);+ // Read once when the sweep settles: the sweep runs behind the create response,+ // so there are no upfront counts to show - the folder's own states close it out.+ const [summary, setSummary] = useState<{+ done: number;+ failed: number;+ } | null>(null);+ const [stalled, setStalled] = useState(false);+ const [opened, setOpened] = useState(0);+ const [cards, setCards] = useState<SweepWallCard[]>([]);+ const [activeFolderId, setActiveFolderId] = useState<string | null>(null);+ // Set when the user cancels; the delivery loop polls it and stands down.+ const cancelRequested = useRef(false);+ const { addFiles } = useFileHandler();+ const { mountLocalFolder } = useFolders();++ // Only offer where it can work: the build must be able to read a file on disk, and Downloads+ // must exist, be permitted, and hold something. Without canListDirectory the results are+ // unreadable here (fetchRunOutputFile throws), so the offer would rewrite the server's own+ // Downloads in place and show the user nothing. Retried because the window can open before+ // the bundled backend is reachable, with a bounded wait so a genuine "no" stops asking.+ useEffect(() => {+ if (!active || !canListDirectory) return;+ let cancelled = false;+ let attempts = 0;+ let timer: ReturnType<typeof setTimeout> | undefined;++ const ask = () => {+ void fetchDownloadsSuggestion()+ .then((next) => {+ if (cancelled) return;+ if (next.available && next.pdfCount > 0) {+ setSuggestion(next);+ // Warm the AI engine while the user reads the offer, so the first classify+ // pays no cold start. Best-effort.+ void apiClient.get("/api/v1/ai/health").catch(() => {});+ return;+ }+ // A definite answer: Downloads is missing, not permitted, or empty. Nothing to wait for.+ })+ .catch(() => {+ // Backend not up yet, access off, or unauthenticated; only the first resolves+ // itself, so retry a while.+ if (cancelled || (attempts += 1) >= 20) return;+ timer = setTimeout(ask, 1500);+ });+ };+ ask();++ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ };+ }, [active]);++ /** Closing resets to the question, so the offer can be reopened and re-run. */+ const close = () => {+ setOpen(false);+ setPhase("asking");+ setProcessed(0);+ setFailed(0);+ setError(null);+ setSummary(null);+ setStalled(false);+ setOpened(0);+ setCards([]);+ setActiveFolderId(null);+ };++ const cancelSweep = async () => {+ cancelRequested.current = true;+ if (activeFolderId) {+ await cancelProcessingRuns(activeFolderId).catch(() => {+ // The loop is already standing down; a failed cancel just lets the+ // remaining runs finish into a folder that is paused anyway.+ });+ }+ close();+ };++ /**+ * Deliver the sweep's results into the workbench as they settle, mirroring the shared+ * delivery's progress onto the card wall and the counts line.+ */+ const trackRuns = useCallback(+ async (policyId: string, excludeRunIds: ReadonlySet<string>) => {+ await deliverSweepResults(policyId, null, addFiles, {+ excludeRunIds,+ isCancelled: () => cancelRequested.current,+ onProgress: (progress) => {+ setProcessed(progress.processed);+ setFailed(progress.failed);+ setOpened(progress.opened);+ if (progress.stalled) setStalled(true);+ },+ // One card per run the sweep actually started, switching state as its run moves.+ onRuns: (runs) => {+ setCards((prev) => mergeRunsIntoCards(prev, runs));+ },+ // Read the discovered document type off the delivered result's metadata.+ onSettled: (settlement) => {+ const name = settlement.fileName?.trim();+ if (!name || settlement.failed || settlement.files.length === 0) {+ return;+ }+ void readClassificationLabelsFromFile(settlement.files[0]).then(+ (labels) => {+ if (!labels || labels.length === 0) return;+ setCards((prev) =>+ prev.map((card) =>+ card.name === name ? { ...card, labels } : card,+ ),+ );+ },+ );+ },+ });+ },+ [addFiles],+ );++ const approve = async () => {+ if (!suggestion) return;+ cancelRequested.current = false;+ setPhase("working");+ try {+ // A folder may already exist over Downloads (the create then adopts it as-is);+ // capture its current runs so the delivery below ignores that history.+ const priorFolder = (await fetchProcessingFolders().catch(() => [])).find(+ (candidate) => candidate.directory === suggestion.directory,+ );+ const baseline = priorFolder+ ? await currentRunIds(priorFolder.id)+ : new Set<string>();+ // Born paused: the offer's promise is one sweep over what is already there.+ // Creation sweeps regardless of the flag; enabled only gates the watch.+ const folder = await saveProcessingFolder({+ directory: suggestion.directory,+ enabled: false,+ steps: [{ operation: CLASSIFY_OPERATION, parameters: {}, assets: {} }],+ });+ setActiveFolderId(folder.id);+ if (cancelRequested.current) {+ // Cancelled during the scan: the runs only exist now, so stop them here or the+ // cancel would be silently outlived.+ await cancelProcessingRuns(folder.id).catch(() => {});+ return;+ }+ // Mount the directory so Downloads exists in the file manager, only where this build can+ // read it (desktop); a plain browser would show a forever-empty folder. Best-effort.+ if (canListDirectory) {+ const segments = suggestion.directory.split(/[/\\]/).filter(Boolean);+ await mountLocalFolder(+ suggestion.directory,+ segments[segments.length - 1] ?? suggestion.directory,+ ).catch(() => {});+ }+ // Created outside the hook's own actions; refresh the shared list.+ void refreshProcessingFolders();+ // The sweep runs behind the create response; delivery stops once the runs settle.+ await trackRuns(folder.id, baseline);+ // Close out from the folder's own per-file states.+ const states = await fetchMountedFiles(folder.id).catch(() => []);+ setSummary({+ done: states.filter((f) => f.state === "done").length,+ failed: states.filter((f) => f.state === "failed").length,+ });+ setPhase("done");+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ setPhase("failed");+ }+ };++ const typesFound = useMemo(() => {+ const ids = new Set<string>();+ for (const card of cards) {+ for (const label of card.labels) ids.add(label);+ }+ return ids.size;+ }, [cards]);++ if (!suggestion) return null;++ const capped = suggestion.pdfCount > suggestion.limit;+ const total = Math.min(suggestion.pdfCount, suggestion.limit);+ const sweepTotal = cards.length || total;+ const settled = processed + failed;++ if (!open) {+ return (+ <div className="downloads-wizard__trigger">+ <Button+ variant="secondary"+ size="sm"+ onClick={() => setOpen(true)}+ leftSection={<FolderSpecialIcon fontSize="small" />}+ >+ {t("processingFolders.downloads.trigger", {+ count: suggestion.pdfCount,+ defaultValue: "Process {{count}} PDFs in Downloads",+ })}+ </Button>+ </div>+ );+ }++ const wall = cards.length > 0 && <SweepRunWall cards={cards} />;++ return (+ <Modal+ open+ // Closing hides the modal while the sweep carries on; reopening shows progress.+ onClose={phase === "working" ? () => setOpen(false) : close}+ width={phase === "asking" ? "sm" : "lg"}+ title={+ <span className="downloads-wizard__title">+ <FolderSpecialIcon fontSize="small" />+ {t("processingFolders.downloads.title", "Organise your Downloads?")}+ </span>+ }+ footer={+ <div className="downloads-wizard__foot">+ {phase === "asking" && (+ <>+ <Button variant="tertiary" size="sm" onClick={close}>+ {t("processingFolders.downloads.notNow", "Not now")}+ </Button>+ <Button size="sm" onClick={() => void approve()}>+ {t(+ "processingFolders.downloads.approve",+ "Process my Downloads",+ )}+ </Button>+ </>+ )}+ {phase === "working" && (+ <>+ <Button+ variant="tertiary"+ size="sm"+ onClick={() => void cancelSweep()}+ >+ {t("processingFolders.downloads.cancelSweep", "Cancel")}+ </Button>+ <Button size="sm" disabled loading>+ {t("processingFolders.downloads.working", "Processing...")}+ </Button>+ </>+ )}+ {(phase === "done" || phase === "failed") && (+ <Button size="sm" onClick={close}>+ {t("processingFolders.downloads.close", "Done")}+ </Button>+ )}+ </div>+ }+ >+ {phase === "asking" && (+ <div className="downloads-wizard__body">+ <p>+ {t("processingFolders.downloads.explain", {+ count: total,+ defaultValue:+ "Stirling can classify the {{count}} PDFs already in your Downloads folder and open the results here.",+ })}+ </p>+ <p className="downloads-wizard__path">{suggestion.directory}</p>+ <ul className="downloads-wizard__facts">+ <li>+ {t(+ "processingFolders.downloads.keepsOriginals",+ "Files are processed in place - and each original is kept, so you can restore it any time.",+ )}+ </li>+ {capped && (+ <li>+ {t("processingFolders.downloads.capped", {+ limit: suggestion.limit,+ found: suggestion.pdfCount,+ defaultValue:+ "You have {{found}} PDFs; the first {{limit}} are processed now and the rest follow.",+ })}+ </li>+ )}+ </ul>+ </div>+ )}++ {phase === "working" && (+ <div className="downloads-wizard__body">+ <p className="downloads-wizard__counts">+ <strong>{settled}</strong>{" "}+ {t("processingFolders.downloads.progressCounts", {+ total: sweepTotal,+ defaultValue: "of {{total}} processed",+ })}+ {typesFound > 0 && (+ <>+ {" · "}+ {t("processingFolders.downloads.typesFound", {+ count: typesFound,+ defaultValue: "{{count}} document types found",+ })}+ </>+ )}+ </p>+ <div className="downloads-wizard__bar" role="progressbar">+ <span+ style={{+ width: `${sweepTotal === 0 ? 0 : Math.round((settled / sweepTotal) * 100)}%`,+ }}+ />+ </div>+ {wall || (+ <div className="downloads-wizard__progress">+ <Loader size="sm" />+ </div>+ )}+ </div>+ )}++ {phase === "done" && (+ <div className="downloads-wizard__body">+ <p className="downloads-wizard__counts">+ <CheckCircleIcon+ className="downloads-wizard__tick"+ fontSize="inherit"+ />{" "}+ {processed + failed === 0+ ? (summary?.failed ?? 0) > 0+ ? t("processingFolders.downloads.stillParked", {+ count: summary?.failed ?? 0,+ defaultValue:+ "{{count}} files failed earlier and were not retried - fix the cause, then run again.",+ })+ : t("processingFolders.downloads.nothingNew", {+ count: summary?.done ?? 0,+ defaultValue:+ "Nothing new to process - these {{count}} files have already been through.",+ })+ : t("processingFolders.downloads.finished", {+ count: processed,+ opened,+ defaultValue:+ "Classified {{count}} files and opened {{opened}} of them here, ready to work on.",+ })}+ {typesFound > 0 && (+ <>+ {" · "}+ {t("processingFolders.downloads.typesFound", {+ count: typesFound,+ defaultValue: "{{count}} document types found",+ })}+ </>+ )}+ </p>+ {failed > 0 && (+ <p className="downloads-wizard__warn">+ {t("processingFolders.downloads.someFailed", {+ count: failed,+ defaultValue:+ "{{count}} could not be processed and were left untouched.",+ })}+ </p>+ )}+ {stalled && (+ <p className="downloads-wizard__warn">+ {t(+ "processingFolders.downloads.stillRunning",+ "Some files are still being processed in the background.",+ )}+ </p>+ )}+ {wall}+ </div>+ )}++ {phase === "failed" && (+ <div className="downloads-wizard__body">+ <p className="downloads-wizard__warn">+ {error ??+ t(+ "processingFolders.downloads.failed",+ "Could not set that up. Your files have not been changed.",+ )}+ </p>+ </div>+ )}+ </Modal>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/EnforceAsPolicyControl.css b/frontend/editor/src/proprietary/components/policies/EnforceAsPolicyControl.cssnew file mode 100644index 0000000000..e9e80f912d--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/EnforceAsPolicyControl.css@@ -0,0 +1,5 @@+.portal-enforce {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+}diff --git a/frontend/editor/src/proprietary/components/policies/EnforceAsPolicyControl.tsx b/frontend/editor/src/proprietary/components/policies/EnforceAsPolicyControl.tsxnew file mode 100644index 0000000000..45d80e59f2--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/EnforceAsPolicyControl.tsx@@ -0,0 +1,50 @@+import { useTranslation } from "react-i18next";+import { InfoTooltip, ToggleSwitch } from "@app/ui";+import "@app/components/policies/EnforceAsPolicyControl.css";++export interface EnforceAsPolicyControlProps {+ /** Org-mandated policy (see Policy.required). */+ required: boolean;+ onRequiredChange: (required: boolean) => void;+ /** Lock the toggle for a non-manager. */+ disabled?: boolean;+ /**+ * The permission check is still loading. The toggle stays locked, but the manager-only tooltip is+ * withheld so a still-loading manager isn't told they lack permission.+ */+ permissionsLoading?: boolean;+}++/**+ * The "Enforce as policy" switch plus the app's standard inline (i) info affordance explaining what+ * it means. Shared by the builder header and the simple wizard so the control reads and behaves+ * identically wherever a pipeline can be made org-mandated.+ */+export function EnforceAsPolicyControl({+ required,+ onRequiredChange,+ disabled = false,+ permissionsLoading = false,+}: EnforceAsPolicyControlProps) {+ const { t } = useTranslation();+ return (+ <span className="portal-enforce">+ <ToggleSwitch+ size="sm"+ checked={required}+ onChange={onRequiredChange}+ disabled={disabled}+ label={t("portal.pipelines.enforce.label")}+ />+ <InfoTooltip+ label={+ disabled && !permissionsLoading+ ? t("portal.pipelines.enforce.managerOnly")+ : t("portal.pipelines.enforce.desc")+ }+ ariaLabel={t("portal.pipelines.enforce.info")}+ position="bottom"+ />+ </span>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.css b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.cssnew file mode 100644index 0000000000..7f4934f3e4--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.css@@ -0,0 +1,117 @@+.folder-setup__title {+ display: inline-flex;+ align-items: center;+ gap: 0.45rem;+}++.folder-setup__body {+ display: flex;+ flex-direction: column;+ gap: 0.8rem;+}++.folder-setup__lead {+ margin: 0;+ font-size: 0.85rem;+ color: var(--c-text-muted);+}++.folder-setup__recipes {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.5rem;+}++/* 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 {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 0.3rem;+ padding: 0.6rem 0.7rem;+ background: var(--c-surface-raised);+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-md, 8px);+ text-align: left;+ 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__recipe:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: 1px;+}++.folder-setup__recipe-icon {+ width: 1.9rem;+ height: 1.9rem;+ border-radius: var(--radius-md, 8px);+ 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;+ 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__steps {+ display: flex;+ flex-direction: column;+}++.folder-setup__step {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 0.5rem 0.15rem;+ border-bottom: 1px solid var(--c-border);+}++.folder-setup__step:last-child {+ border-bottom: 0;+}++.folder-setup__step-label {+ display: flex;+ flex-direction: column;+ font-size: 0.86rem;+}++.folder-setup__step-label small {+ color: var(--c-text-subtle);+ font-size: 0.75rem;+}++.folder-setup__error {+ margin: 0;+ font-size: 0.82rem;+ color: var(--c-danger, var(--c-text));+}++.folder-setup__foot {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 0.5rem;+}diff --git a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsxnew file mode 100644index 0000000000..f445cc9e56--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx@@ -0,0 +1,234 @@+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";++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.+ */+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 same catalogue Processor's gallery assembles, with no saved-policy+ // decoration: a folder setup always starts from the template.+ const entries = useMemo<CatalogueEntry[]>(+ () =>+ POLICY_CATEGORIES.flatMap((category) => {+ const config = POLICY_CONFIG[category.id];+ return config ? [{ 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>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/PipelineTemplateCard.tsx b/frontend/editor/src/proprietary/components/policies/PipelineTemplateCard.tsxnew file mode 100644index 0000000000..087b1ee182--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/PipelineTemplateCard.tsx@@ -0,0 +1,56 @@+import { useTranslation } from "react-i18next";+import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded";+import LockOutlinedIcon from "@mui/icons-material/LockOutlined";+import { OptionCard } from "@app/ui";+import type { CatalogueEntry } from "@app/policies/catalog";+import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";++interface PipelineTemplateCardProps {+ entry: CatalogueEntry;+ onOpen: (entry: CatalogueEntry) => void;+ /** Setup is unavailable (e.g. the AI engine is off): shown, but not openable. */+ locked?: boolean;+ /** Chip text explaining why setup is locked (e.g. "Requires AI engine"). */+ lockedLabel?: string;+}++/**+ * A template in the Pipelines gallery: a ready-made starting point that opens the simple, guided+ * setup. A thin adapter over the {@link OptionCard} primitive - it maps the catalogue category to+ * the card's icon/title/blurb and picks the CTA vs the disabled note (coming soon / AI-locked).+ */+export function PipelineTemplateCard({+ entry,+ onOpen,+ locked = false,+ lockedLabel,+}: PipelineTemplateCardProps) {+ const { t } = useTranslation();+ const { category } = entry;+ const comingSoon = category.comingSoon === true;+ const disabled = comingSoon || locked;++ return (+ <OptionCard+ icon={policyCategoryIcon(category.id)}+ title={t(category.label)}+ description={t(category.desc)}+ disabled={disabled}+ onSelect={() => onOpen(entry)}+ cta={+ <>+ {t("portal.pipelines.templates.setUp")}+ <ArrowForwardRoundedIcon style={{ fontSize: "1rem" }} />+ </>+ }+ note={+ <>+ <LockOutlinedIcon style={{ fontSize: "0.95rem" }} />+ {comingSoon+ ? t("portal.policies.card.comingSoon")+ : (lockedLabel ?? t("portal.policies.card.requiresAiEngine"))}+ </>+ }+ />+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/PolicyCategoryBadge.css b/frontend/editor/src/proprietary/components/policies/PolicyCategoryBadge.cssnew file mode 100644index 0000000000..ee0b6dde44--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/PolicyCategoryBadge.css@@ -0,0 +1,15 @@+/* Neutral gray rounded icon badge for a policy category. Lives with the+ component so every consumer gets the styling without importing a view CSS. */+.pcat-badge {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ flex-shrink: 0;+ border-radius: var(--radius-lg);+ background: var(--c-surface-sunken);+ color: var(--c-text-subtle);+ /* The shared MUI outline glyph inherits its size from here. */+ font-size: 1.15rem;+}diff --git a/frontend/editor/src/proprietary/components/policies/PolicyCategoryBadge.tsx b/frontend/editor/src/proprietary/components/policies/PolicyCategoryBadge.tsxnew file mode 100644index 0000000000..58d5f916af--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/PolicyCategoryBadge.tsx@@ -0,0 +1,15 @@+import type { PolicyCategory } from "@app/policies/catalog";+import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";+import "@app/components/policies/PolicyCategoryBadge.css";++export function PolicyCategoryBadge({+ category,+}: {+ category: PolicyCategory;+}) {+ return (+ <span className="pcat-badge" aria-hidden>+ {policyCategoryIcon(category.id)}+ </span>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.cssnew file mode 100644index 0000000000..a0454174ab--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css@@ -0,0 +1,71 @@+/* The setup wizard's own chrome. The portal's Policies view carries sibling+ rules for its detail panel; these are the wizard's, colocated with the shared+ component so every surface that renders it gets them. */++.portal-policies__wizard-title {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-policies__wizard-foot {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ width: 100%;+}++.portal-policies__wizard-banner {+ margin-top: 0.75rem;+}++.portal-policies__wizard-section {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ margin-top: 1rem;+}++.portal-policies__wizard-desc {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--c-text-subtle);+}++.portal-policies__wizard-heading {+ margin: 0.75rem 0 0;+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--c-text-subtle);+ font-weight: 600;+}++/* "Enforce as policy" - the last choice in the simple wizard, set off from the settings above. */+.portal-policies__wizard-enforce {+ margin-top: 0.75rem;+ padding-top: 0.875rem;+ border-top: 1px solid var(--c-border-subtle);+}++/* The tool list reads as one surface with dividers - a set of capabilities,+ not a chain of distinct tools. Config reveals inline beneath an enabled row. */+.portal-policies__capabilities {+ display: flex;+ flex-direction: column;+}++.portal-policies__capability {+ padding: 0.75rem 0.875rem;+}++.portal-policies__capability + .portal-policies__capability {+ border-top: 1px solid var(--c-border);+}++.portal-policies__capability[data-on] .portal-policies__capability-config {+ border-top: 1px dashed var(--c-border);+ padding-top: 0.75rem;+ margin-top: 0.75rem;+}diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsxnew file mode 100644index 0000000000..703682a671--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx@@ -0,0 +1,563 @@+import { 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";+import { SettingsRow } from "@app/ui/SettingsRow";+import { EnforceAsPolicyControl } from "@app/components/policies/EnforceAsPolicyControl";+import {+ humanizeEndpoint,+ type CatalogueEntry,+ type PipelineStep,+ type PolicySetupResult,+} from "@app/policies/catalog";+import {+ policyEndpoint,+ policyStepFromWire,+ policyStepToWire,+ type PolicyParams,+ type PolicyToolId,+ type PolicyToolStep,+} from "@app/policies/operations";+import { resolveRunOn } from "@app/policies/runOn";+import { PolicyCategoryBadge } from "@app/components/policies/PolicyCategoryBadge";+import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";+import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";+import { ClassificationLabelsSection } from "@app/components/policies/ClassificationLabelsSection";+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;+ submit: () => void;+ submitting: boolean;+ error: string | null;+ /** False while no step is enabled, when submitting would be a no-op. */+ canSubmit: boolean;+}++interface PolicySetupWizardProps {+ /** The category being configured, or null when closed. */+ entry: CatalogueEntry | null;+ onClose: () => void;+ /** Fires on submit with settings + built steps; a rejection re-enables submit and+ * surfaces the failure. */+ onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;+ /** Fires when the user asks to Customise: hands the unsaved settings to the full builder.+ * Surfaces without a builder omit it and the button hides. */+ onCustomise?: (entry: CatalogueEntry, result: PolicySetupResult) => void;+ /** Whether a Purview tenant is connected; gates the Purview-backed steps. */+ hasPurviewConnection?: boolean;+ /** Renders the Purview step's inline config. Portal-only; without it the step shows bare. */+ purviewConfig?: (props: {+ parameters: PolicyParams<"purviewApplyLabel">;+ onChange: (params: PolicyParams<"purviewApplyLabel">) => void;+ }) => ReactNode;+ /** Turns a submit failure into user-facing copy; defaults to the error's own message. */+ formatError?: (e: unknown) => string;+ /** Whether the org-enforcement choice applies on this surface (it doesn't for folders). */+ enforceControl?: 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. */+ permissionsLoading?: boolean;+ /** Frame the form yourself: receives the middle content and submit state, returns the+ * chrome. Without it the portal's own modal renders. */+ children?: (frame: PolicySetupFrame) => ReactNode;+}++type ToolState = PolicyToolStep & { enabled: boolean };++/** Resolve each field's effective value: saved override, else definition default. */+function resolveFieldValues(+ entry: CatalogueEntry,+): Record<string, boolean | string | string[]> {+ const saved = entry.policy?.state.fieldValues ?? {};+ const out: Record<string, boolean | string | string[]> = {};+ for (const f of entry.config.fields) out[f.key] = saved[f.key] ?? f.value;+ return out;+}++/** Seed the workflow's tools: a configured policy's saved steps win (editing round-trips),+ * else the category preset's default chain. */+// Temporary until the catalogue carries a defaultEnabled flag: steps that cannot work+// unconfigured start off. Purview needs a tenant connection and a label GUID.+const DISABLED_BY_DEFAULT = new Set<PolicyToolId>([+ "watermark",+ "purviewApplyLabel",+ "purviewReadLabel",+ "externalApiCall",+]);++// Hidden without a Purview tenant connection; offered, they could only fail.+const PURVIEW_TOOLS = new Set<PolicyToolId>([+ "purviewApplyLabel",+ "purviewReadLabel",+]);++/**+ * Policy-facing framing per capability: labels describe what the policy DOES to a document,+ * not the underlying tool. Endpoints with no entry fall back to the humanised endpoint name.+ */+const CAPABILITY_META: Record<+ PolicyToolId,+ { labelKey: string; labelEn: string; descKey: string; descEn: string }+> = {+ redact: {+ labelKey: "portal.policies.wizard.capability.redact.label",+ labelEn: "Redact sensitive information",+ descKey: "portal.policies.wizard.capability.redact.desc",+ descEn:+ "Finds and blacks out sensitive details — like Social Security and card numbers — so they can't be read.",+ },+ sanitize: {+ labelKey: "portal.policies.wizard.capability.sanitize.label",+ labelEn: "Strip active content",+ descKey: "portal.policies.wizard.capability.sanitize.desc",+ descEn:+ "Removes hidden JavaScript so nothing can run automatically when the document is opened.",+ },++ timestampPdf: {+ labelKey: "portal.policies.wizard.capability.timestampPdf.label",+ labelEn: "Add a trusted timestamp",+ descKey: "portal.policies.wizard.capability.timestampPdf.desc",+ descEn:+ "Proves the document existed in this exact form at a point in time, using an independent timestamp authority. Only a hash is sent - the document never leaves your server.",+ },+ watermark: {+ labelKey: "portal.policies.wizard.capability.watermark.label",+ labelEn: "Apply a watermark",+ descKey: "portal.policies.wizard.capability.watermark.desc",+ descEn: "Stamps a visible mark (e.g. “Confidential”) across every page.",+ },+ ocr: {+ labelKey: "portal.policies.wizard.capability.ocr.label",+ labelEn: "Make text searchable",+ descKey: "portal.policies.wizard.capability.ocr.desc",+ descEn: "Runs OCR so scanned pages become selectable, searchable text.",+ },+ flatten: {+ labelKey: "portal.policies.wizard.capability.flatten.label",+ labelEn: "Flatten the document",+ descKey: "portal.policies.wizard.capability.flatten.desc",+ descEn:+ "Merges form fields and annotations into the page so they can't be edited.",+ },+ compress: {+ labelKey: "portal.policies.wizard.capability.compress.label",+ labelEn: "Reduce file size",+ descKey: "portal.policies.wizard.capability.compress.desc",+ descEn: "Compresses the document to a smaller file size.",+ },+ classify: {+ labelKey: "portal.policies.wizard.capability.classify.label",+ labelEn: "Classify the document",+ descKey: "portal.policies.wizard.capability.classify.desc",+ descEn:+ "Identifies the document's type from your team's labels and tags it, so it files and searches by category.",+ },+ purviewApplyLabel: {+ labelKey: "portal.policies.wizard.capability.purviewApplyLabel.label",+ labelEn: "Apply a Microsoft Purview sensitivity label",+ descKey: "portal.policies.wizard.capability.purviewApplyLabel.desc",+ descEn:+ "Marks the document with one of your organisation's Purview labels, so Purview-aware tools recognise how sensitive it is.",+ },+ purviewReadLabel: {+ labelKey: "portal.policies.wizard.capability.purviewReadLabel.label",+ labelEn: "Read the document's Purview label",+ descKey: "portal.policies.wizard.capability.purviewReadLabel.desc",+ descEn:+ "Reports the Purview label a document already carries, so the rest of the policy can act on how sensitive it is.",+ },+ externalApiCall: {+ labelKey: "portal.policies.wizard.capability.externalApiCall.label",+ labelEn: "Send the document to another system",+ descKey: "portal.policies.wizard.capability.externalApiCall.desc",+ descEn:+ "Hands the document to a system you have connected, and records what it answered.",+ },+};++function seedTools(entry: CatalogueEntry): ToolState[] {+ const savedSteps = entry.policy?.steps ?? [];+ const savedByTool = new Map<PolicyToolId, PolicyToolStep>();+ for (const wire of savedSteps) {+ const step = policyStepFromWire(wire);+ if (step) savedByTool.set(step.toolId, step);+ }+ // defaultOperations is the canonical list (so tools added later still show on edit); a saved+ // step's params win over the preset.+ return entry.config.defaultOperations.map((preset) => {+ const saved = savedByTool.get(preset.toolId);+ return {+ ...(saved ?? preset),+ enabled: saved+ ? true+ : savedSteps.length > 0+ ? false+ : !DISABLED_BY_DEFAULT.has(preset.toolId),+ };+ });+}++/**+ * 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.+ */+export function PolicySetupWizard({+ entry,+ onClose,+ onSubmit,+ onCustomise,+ hasPurviewConnection,+ purviewConfig,+ formatError,+ enforceControl,+ 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}+ onCustomise={onCustomise}+ hasPurviewConnection={hasPurviewConnection}+ purviewConfig={purviewConfig}+ formatError={formatError}+ enforceControl={enforceControl}+ canManagePolicies={canManagePolicies}+ permissionsLoading={permissionsLoading}+ >+ {children}+ </PolicySetupWizardBody>+ ) : null;+}++function PolicySetupWizardBody({+ entry,+ onClose,+ onSubmit,+ onCustomise,+ hasPurviewConnection = false,+ purviewConfig,+ formatError,+ enforceControl = true,+ canManagePolicies = true,+ permissionsLoading = false,+ children,+}: {+ entry: CatalogueEntry;+ onClose: () => void;+ onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;+ onCustomise?: (entry: CatalogueEntry, result: PolicySetupResult) => void;+ hasPurviewConnection?: boolean;+ purviewConfig?: (props: {+ parameters: PolicyParams<"purviewApplyLabel">;+ onChange: (params: PolicyParams<"purviewApplyLabel">) => void;+ }) => ReactNode;+ formatError?: (e: unknown) => string;+ enforceControl?: boolean;+ canManagePolicies?: boolean;+ permissionsLoading?: boolean;+ children?: (frame: PolicySetupFrame) => ReactNode;+}) {+ const { t } = useTranslation();++ const { category, config, policy } = entry;+ const isEdit = policy != null;+ const isClassification = category.id === "classification";++ 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);+ // A template is a policy by nature, where a failure blocks the file rather than waving it+ // through, so a new one defaults to required. Editing preserves what was saved.+ const [required, setRequired] = useState(policy?.state.required ?? true);+ 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(+ () =>+ tools.filter(+ (tl) =>+ !PURVIEW_TOOLS.has(tl.toolId) || hasPurviewConnection || tl.enabled,+ ),+ [tools, hasPurviewConnection],+ );++ // Derive from the visible list: a hidden step is never submitted (hidden implies disabled).+ const enabledTools = useMemo(+ () => visibleTools.filter((tl) => tl.enabled),+ [visibleTools],+ );++ function setToolEnabled(toolId: PolicyToolId, enabled: boolean) {+ setTools((prev) =>+ prev.map((tl) => (tl.toolId === toolId ? { ...tl, enabled } : tl)),+ );+ }++ function setToolParams<Id extends PolicyToolId>(+ toolId: Id,+ params: PolicyParams<Id>,+ ) {+ setTools((prev) =>+ prev.map((tl) =>+ tl.toolId === toolId ? ({ ...tl, params } as ToolState) : tl,+ ),+ );+ }++ /** The wizard's current state as a submit result: shared by Save and Customise. */+ function collectResult(): PolicySetupResult {+ const steps: PipelineStep[] = enabledTools.map((tl) =>+ policyStepToWire(tl),+ );+ return {+ required,+ // 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,+ runsOnEditor: true,+ fieldValues,+ sources: policy?.state.sources ?? [],+ scopeTypes,+ reviewerEmail,+ outputMode,+ outputName: outputName.trim(),+ outputNamePosition,+ runOn,+ maxRetries,+ retryDelayMinutes,+ steps,+ };+ }++ // No "needs at least one tool" guard here: the builder has its own.+ function customise() {+ onCustomise?.(entry, collectResult());+ }++ async function submit() {+ if (submitting) return;+ if (enabledTools.length === 0) {+ setError(t("portal.policies.wizard.errors.noTools"));+ return;+ }+ setError(null);+ setSubmitting(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"));+ }+ }++ const canSubmit = enabledTools.length > 0;+ const content = (+ <>+ {error && (+ <Banner+ tone="danger"+ description={error}+ className="portal-policies__wizard-banner"+ />+ )}++ {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>+ <h3 className="portal-policies__wizard-heading">+ {t(+ "portal.policies.wizard.classification.labelsHeading",+ "Classification labels",+ )}+ </h3>+ <ClassificationLabelsSection />+ </div>+ )}++ {!isClassification && (+ <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>+ <Card padding="none">+ <div className="portal-policies__capabilities">+ {visibleTools.map((tl) => {+ const meta = CAPABILITY_META[tl.toolId];+ const label = meta+ ? t(meta.labelKey, meta.labelEn)+ : humanizeEndpoint(policyEndpoint(tl.toolId), t);+ const description = meta+ ? t(meta.descKey, meta.descEn)+ : undefined;+ return (+ <div+ key={tl.toolId}+ className="portal-policies__capability"+ data-on={tl.enabled || undefined}+ >+ <SettingsRow+ label={label}+ description={description}+ control={+ <ToggleSwitch+ size="sm"+ checked={tl.enabled}+ onChange={(checked) =>+ setToolEnabled(tl.toolId, checked)+ }+ label=""+ />+ }+ />+ {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 === "purviewApplyLabel" &&+ purviewConfig?.({+ parameters: tl.params,+ onChange: (params) =>+ setToolParams("purviewApplyLabel", params),+ })}+ </div>+ )}+ </div>+ );+ })}+ </div>+ </Card>+ </div>+ )}++ {enforceControl && (+ <div className="portal-policies__wizard-enforce">+ <EnforceAsPolicyControl+ required={required}+ onRequiredChange={setRequired}+ disabled={readOnly}+ permissionsLoading={permissionsLoading}+ />+ </div>+ )}+ </>+ );+ if (children) {+ return children({ content, submit, submitting, error, canSubmit });+ }+ return (+ <Modal+ open+ onClose={onClose}+ width="lg"+ title={+ <span className="portal-policies__wizard-title">+ <PolicyCategoryBadge category={category} />+ {isEdit+ ? t("portal.policies.wizard.title.edit", {+ category: t(category.label),+ })+ : t("portal.policies.wizard.title.setUp", {+ category: t(category.label),+ })}+ </span>+ }+ subtitle={t(config.summary)}+ footer={+ <div className="portal-policies__wizard-foot">+ <Button variant="tertiary" size="sm" onClick={onClose}>+ {t("portal.policies.wizard.actions.cancel")}+ </Button>+ <Button+ variant="tertiary"+ size="sm"+ onClick={customise}+ disabled={!onCustomise}+ title={+ onCustomise+ ? undefined+ : t(+ "portal.policies.wizard.actions.customiseUnavailable",+ "The full builder lives on Processor",+ )+ }+ leftSection={<TuneRoundedIcon style={{ fontSize: "1.05rem" }} />}+ >+ {t("portal.policies.wizard.actions.customise")}+ </Button>+ <Button+ size="sm"+ style={{ marginLeft: "auto" }}+ onClick={submit}+ loading={submitting}+ disabled={readOnly}+ >+ {isEdit+ ? t("portal.policies.wizard.actions.saveChanges")+ : t("portal.policies.wizard.actions.enablePolicy")}+ </Button>+ </div>+ }+ >+ {content}+ </Modal>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/SweepRunWall.css b/frontend/editor/src/proprietary/components/policies/SweepRunWall.cssnew file mode 100644index 0000000000..67fda5df63--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/SweepRunWall.css@@ -0,0 +1,127 @@+/* ---- The card wall: every file in a sweep, lighting up as its run settles. ---- */++.sweep-wall {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));+ gap: 0.5rem;+ max-height: 55vh;+ overflow-y: auto;+ padding-right: 0.25rem;+}++.sweep-wall__card {+ display: flex;+ flex-direction: column;+ gap: 0.3rem;+ min-height: 4.4rem;+ padding: 0.5rem 0.6rem;+ background: var(--c-surface);+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-sm, 4px);+ transition:+ border-color 0.25s ease,+ opacity 0.25s ease;+}++.sweep-wall__card--pending {+ opacity: 0.65;+}++.sweep-wall__card--running {+ border-color: var(--c-primary);+}++.sweep-wall__card--done {+ border-color: var(--c-success, var(--c-primary));+}++.sweep-wall__card--failed {+ border-color: var(--c-danger-text, var(--c-border-subtle));+ opacity: 0.8;+}++.sweep-wall__card-name {+ font-size: 0.72rem;+ color: var(--c-text);+ word-break: break-all;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.sweep-wall__card-status {+ display: flex;+ align-items: center;+ gap: 0.3rem;+ min-height: 1.15rem;+ font-size: 0.68rem;+ color: var(--c-text-muted);+}++/* Lightweight CSS spinner — the wall can hold a hundred cards, so no widget per card. */+.sweep-wall__spin {+ width: 0.7rem;+ height: 0.7rem;+ flex: none;+ border: 2px solid var(--c-border-subtle);+ border-top-color: var(--c-primary);+ border-radius: 50%;+ animation: sweep-wall-spin 0.7s linear infinite;+}++@keyframes sweep-wall-spin {+ to {+ transform: rotate(360deg);+ }+}++/* The reveal: the discovered document type, popping in as the run settles. */+.sweep-wall__chip {+ display: inline-flex;+ align-items: center;+ max-width: 100%;+ padding: 0.1rem 0.45rem;+ border: 1px solid var(--c-primary);+ border-radius: 999px;+ color: var(--c-primary);+ font-size: 0.68rem;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ animation: sweep-wall-chip-in 0.3s ease;+}++@keyframes sweep-wall-chip-in {+ from {+ opacity: 0;+ transform: scale(0.8);+ }+ to {+ opacity: 1;+ transform: scale(1);+ }+}++/* ---- The one-line strip a working folder raises while a sweep runs. ---- */++.sweep-wall__panel {+ display: flex;+ align-items: center;+ gap: 0.45rem;+ margin-bottom: 0.75rem;+ padding: 0.45rem 0.7rem;+ background: var(--c-surface-raised, var(--c-surface));+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-sm, 4px);+ font-size: 0.82rem;+ font-weight: 600;+ color: var(--c-text);+}++.sweep-wall__panel-count {+ margin-left: auto;+ font-variant-numeric: tabular-nums;+ font-weight: 500;+ color: var(--c-text-muted);+}diff --git a/frontend/editor/src/proprietary/components/policies/SweepRunWall.tsx b/frontend/editor/src/proprietary/components/policies/SweepRunWall.tsxnew file mode 100644index 0000000000..7528491304--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/SweepRunWall.tsx@@ -0,0 +1,165 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { useLabelName } from "@app/data/labelDisplay";+import {+ fetchProcessingFolderRuns,+ type ProcessingFolderRun,+} from "@app/services/processingFolderApi";+import "@app/components/policies/SweepRunWall.css";++const TERMINAL = ["COMPLETED", "FAILED", "CANCELLED"];++/** How often the live wall re-reads the runs feed while it is watching. */+const POLL_MS = 2000;++/** Settled-only polls before a finished wall stands down. */+const IDLE_POLLS = 3;++export type SweepCardPhase = "pending" | "running" | "done" | "failed";++export interface SweepWallCard {+ name: string;+ state: SweepCardPhase;+ /** Classification label ids, when the caller reads them off delivered results. */+ labels: string[];+}++/** Fold one poll of the runs feed into the wall's cards; a done card never regresses. */+export function mergeRunsIntoCards(+ prev: SweepWallCard[],+ runs: ProcessingFolderRun[],+): SweepWallCard[] {+ const byName = new Map(prev.map((card) => [card.name, card]));+ const next: SweepWallCard[] = [...prev];+ for (const run of [...runs].reverse()) {+ const name = run.fileName?.trim();+ if (!name) continue;+ const terminal = TERMINAL.includes(run.status);+ const state: SweepCardPhase = !terminal+ ? "running"+ : run.status === "COMPLETED"+ ? "done"+ : "failed";+ const existing = byName.get(name);+ if (!existing) {+ const card: SweepWallCard = { name, state, labels: [] };+ byName.set(name, card);+ next.push(card);+ } else if (existing.state !== state && existing.state !== "done") {+ const index = next.indexOf(existing);+ next[index] = { ...existing, state };+ byName.set(name, next[index]);+ }+ }+ return next;+}++/** The wall itself: every document a sweep took on, lighting up as its run settles.+ * Pure render over the caller's cards, so it works from any feed. */+export function SweepRunWall({ cards }: { cards: SweepWallCard[] }) {+ const { t } = useTranslation();+ const labelName = useLabelName();+ if (cards.length === 0) return null;+ return (+ <div className="sweep-wall">+ {cards.map((card) => (+ <div+ key={card.name}+ className={`sweep-wall__card sweep-wall__card--${card.state}`}+ >+ <span className="sweep-wall__card-name">{card.name}</span>+ <span className="sweep-wall__card-status">+ {card.state === "running" && (+ <span className="sweep-wall__spin" aria-hidden />+ )}+ {card.state === "pending" &&+ t("processingFolders.wall.waiting", "Queued...")}+ {card.state === "failed" &&+ t("processingFolders.wall.failed", "Failed")}+ {card.state === "done" &&+ (card.labels.length > 0 ? (+ card.labels.map((label) => (+ <span key={label} className="sweep-wall__chip">+ {labelName(label)}+ </span>+ ))+ ) : (+ <>{t("processingFolders.wall.done", "Done")}</>+ ))}+ </span>+ </div>+ ))}+ </div>+ );+}++export interface FolderSweepWallProps {+ /** The processing record whose runs to watch; absent renders nothing. */+ policyId?: string;+}++/**+ * A working folder's live sweep, wherever it came from. Polls the runs feed and raises a+ * one-line strip only while runs execute: the grid below already wears each file's badge.+ */+export function FolderSweepWall({ policyId }: FolderSweepWallProps) {+ const { t } = useTranslation();+ const [cards, setCards] = useState<SweepWallCard[]>([]);+ const [visible, setVisible] = useState(false);+ const [anyRunning, setAnyRunning] = useState(false);+ // Old terminal runs sit in the feed forever; the wall only wakes for a run+ // it has seen live, so opening a folder never replays finished history.+ const wokeRef = useRef(false);+ const idleRef = useRef(0);++ useEffect(() => {+ setCards([]);+ setVisible(false);+ setAnyRunning(false);+ wokeRef.current = false;+ idleRef.current = 0;+ if (!policyId) return;+ let cancelled = false;+ const tick = async () => {+ const runs = await fetchProcessingFolderRuns(policyId).catch(+ () => [] as ProcessingFolderRun[],+ );+ if (cancelled) return;+ const live = runs.some((run) => !TERMINAL.includes(run.status));+ setAnyRunning(live);+ if (live) {+ wokeRef.current = true;+ idleRef.current = 0;+ setVisible(true);+ }+ if (wokeRef.current) {+ setCards((prev) => mergeRunsIntoCards(prev, runs));+ if (!live && ++idleRef.current >= IDLE_POLLS) {+ wokeRef.current = false;+ setVisible(false);+ setCards([]);+ }+ }+ };+ void tick();+ const timer = setInterval(() => void tick(), POLL_MS);+ return () => {+ cancelled = true;+ clearInterval(timer);+ };+ }, [policyId]);++ if (!visible || cards.length === 0) return null;+ const settled = cards.filter(+ (card) => card.state === "done" || card.state === "failed",+ ).length;+ return (+ <div className="sweep-wall__panel">+ {anyRunning && <span className="sweep-wall__spin" aria-hidden />}+ <span>{t("processingFolders.wall.title", "Processing this folder")}</span>+ <span className="sweep-wall__panel-count">+ {settled}/{cards.length}+ </span>+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx b/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsxnew file mode 100644index 0000000000..e6cb0da0fa--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx@@ -0,0 +1,17 @@+import { type SidebarProcessingSlotProps } from "@core/components/shared/SidebarProcessingSlot";+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.+ */+export function SidebarProcessingSlot({+ collapsed,+}: SidebarProcessingSlotProps) {+ if (collapsed) return null;+ return <DownloadsProcessingWizard />;+}diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsxindex 8747fe0dfe..bd3fb7a322 100644--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx+++ b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx@@ -835,7 +835,7 @@ export function WatchedFolderManagementModal({>{isEditMode? t("watchedFolders.modal.saveChanges", "Save changes")- : t("watchedFolders.modal.createFolder", "Create folder")}+ : t("watchedFolders.modal.createFolder", "New folder")}</Button></Group></div>diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts b/frontend/editor/src/proprietary/hooks/useProcessingFolders.tsnew file mode 100644index 0000000000..9fcc2acdfc--- /dev/null+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts@@ -0,0 +1,343 @@+import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";+import {+ CLASSIFY_OPERATION,+ classificationDefaults,+ deleteProcessingFolder,+ fetchMountedFiles,+ fetchProcessingFolderRuns,+ fetchProcessingFolders,+ retryMountedFile,+ revertAllMountedFiles,+ revertMountedFile,+ saveProcessingFolder,+ sweepProcessingFolder,+ type ProcessingFolder,+} from "@app/services/processingFolderApi";+import { useFileHandler } from "@app/hooks/useFileHandler";+import {+ currentRunIds,+ deliverSweepResults,+} from "@app/services/processingRunDelivery";+import { folderKind, type FolderRecord } from "@app/types/folder";+// 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,+ ProcessingFolderState,+ ProcessingFoldersApi,+ 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";++/** 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 inFlight: Promise<void> | null = null;+const listeners = new Set<() => void>();++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++/** Snapshot identity only changes when the list is replaced, so consumers re-render on real news. */+function getSnapshot(): ProcessingFolder[] {+ return folders;+}++/** Load the list, sharing one request across concurrent callers; `force` bypasses an+ * in-flight read so a mutation observes its own effect. */+function load(force = false): Promise<void> {+ if (inFlight && !force) return inFlight;+ const request = fetchProcessingFolders()+ .then((next) => {+ folders = next;+ })+ .catch(() => {+ // Storage or login off, or unauthenticated: the files page works without these.+ folders = [];+ })+ .finally(() => {+ if (inFlight === request) inFlight = null;+ listeners.forEach((listener) => listener());+ });+ inFlight = request;+ 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+ * rather than patching locally, so the list reflects what the server composed.+ */+export function useProcessingFolders(): ProcessingFoldersApi {+ const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+ const { addFiles } = useFileHandler();++ useEffect(() => {+ void load();+ }, []);++ const recordFor = useCallback(+ (folder: FolderRecord): ProcessingFolder | undefined => {+ switch (folderKind(folder)) {+ case "local": {+ if (!folder.directory) return undefined;+ const key = directoryKey(folder.directory);+ return current.find(+ (record) =>+ record.directory && directoryKey(record.directory) === key,+ );+ }+ case "virtual":+ // Browser-owned folders live only in this browser; the server has no record of them.+ return undefined;+ default:+ return current.find((record) => record.folderId === folder.id);+ }+ },+ [current],+ );++ const recordSummaryFor = useCallback(+ (folder: FolderRecord): ProcessingRecordSummary | undefined => {+ const record = recordFor(folder);+ if (!record) return undefined;+ return {+ id: record.id,+ enabled: record.enabled,+ steps: record.steps.map((step) => ({+ operation: step.operation,+ parameters: step.parameters ?? {},+ assets: step.assets,+ })),+ };+ },+ [recordFor],+ );++ const stateFor = useCallback(+ (folder: FolderRecord): ProcessingFolderState | undefined => {+ const record = recordFor(folder);+ if (!record) return undefined;+ const outputDirectory = record.output?.["directory"];+ return {+ id: record.id,+ enabled: record.enabled,+ outputDirectory:+ typeof outputDirectory === "string" && outputDirectory+ ? outputDirectory+ : undefined,+ };+ },+ [recordFor],+ );++ const enabledFolderIds = useMemo(() => {+ const ids = new Set<string>();+ for (const record of current) {+ if (record.enabled && record.folderId) ids.add(record.folderId);+ }+ return ids as ReadonlySet<string>;+ }, [current]);++ const anyEnabled = useMemo(+ () => current.some((record) => record.enabled),+ [current],+ );++ const enable = useCallback(+ async (folder: FolderRecord) => {+ // A paused pair resumes with its own steps and its history intact;+ // only a folder with no pair composes a fresh classification default.+ const paused = recordFor(folder);+ if (paused && !paused.enabled) {+ // Captured before the resume so its delivery ignores the feed's older runs.+ const baseline = await currentRunIds(paused.id);+ await saveProcessingFolder({+ id: paused.id,+ folderId: paused.folderId ?? undefined,+ directory: paused.directory ?? undefined,+ enabled: true,+ steps: paused.steps,+ output: paused.output,+ });+ // Resume sweeps behind the response; pull a mount's on-disk results into the workbench.+ if (folderKind(folder) === "local") {+ void deliverSweepResults(paused.id, null, addFiles, {+ excludeRunIds: baseline,+ });+ }+ await load(true);+ return;+ }+ switch (folderKind(folder)) {+ case "local": {+ const saved = await saveProcessingFolder({+ directory: folder.directory ?? "",+ enabled: true,+ steps: [+ { operation: CLASSIFY_OPERATION, parameters: {}, assets: {} },+ ],+ });+ // The sweep runs behind the create response — no run count to wait on; pull+ // the on-disk results into the workbench as they settle.+ void deliverSweepResults(saved.id, null, addFiles);+ break;+ }+ case "virtual":+ return;+ default:+ await saveProcessingFolder(classificationDefaults(folder.id));+ }+ await load(true);+ },+ [recordFor, addFiles],+ );++ // Pause, never delete: the kept history means resuming picks up only what is new.+ const disable = useCallback(+ async (folder: FolderRecord) => {+ const existing = recordFor(folder);+ if (!existing) return;+ await saveProcessingFolder({+ id: existing.id,+ folderId: existing.folderId ?? undefined,+ directory: existing.directory ?? undefined,+ enabled: false,+ steps: existing.steps,+ output: existing.output,+ });+ await load(true);+ },+ [recordFor],+ );++ const remove = useCallback(+ async (folder: FolderRecord) => {+ const existing = recordFor(folder);+ if (!existing) return;+ await deleteProcessingFolder(existing.id);+ await load(true);+ },+ [recordFor],+ );++ const listActiveRuns = useCallback(+ async (recordId: string): Promise<ProcessingRunInfo[]> => {+ const TERMINAL = ["COMPLETED", "FAILED", "CANCELLED"];+ const runs = await fetchProcessingFolderRuns(recordId).catch(() => []);+ return runs+ .filter((run) => run.runId && !TERMINAL.includes(run.status))+ .map((run) => ({+ runId: run.runId!,+ fileName: run.fileName ?? null,+ currentStep: run.currentStep ?? 0,+ stepCount: run.stepCount ?? 0,+ }));+ },+ [],+ );++ const listFiles = useCallback(+ async (recordId: string): Promise<MountedFileState[]> =>+ (await fetchMountedFiles(recordId)).map((file) => ({+ name: file.name,+ state: file.state,+ hasOriginal: file.hasOriginal,+ })),+ [],+ );++ const retryFile = useCallback(+ async (recordId: string, name: string) => retryMountedFile(recordId, name),+ [],+ );++ const revertFile = useCallback(async (recordId: string, name: string) => {+ await revertMountedFile(recordId, name);+ // Revert pauses the folder server-side; reload so the pause shows at once.+ await load(true);+ }, []);++ const revertAll = useCallback(+ async (folder: FolderRecord) => {+ const existing = recordFor(folder);+ if (!existing) return undefined;+ const outcome = await revertAllMountedFiles(existing.id);+ // Revert pauses the folder server-side; reload so the pause shows at once.+ await load(true);+ return outcome;+ },+ [recordFor],+ );++ const sweep = useCallback(+ async (folder: FolderRecord) => {+ const existing = recordFor(folder);+ if (!existing) return;+ const outcome = await sweepProcessingFolder(existing.id);+ // A mount's results land on disk where nothing shows them; a storage folder's+ // replace in place, already visible.+ if (folderKind(folder) === "local" && outcome.runIds.length > 0) {+ void deliverSweepResults(existing.id, outcome.runIds.length, addFiles, {+ includeRunIds: new Set(outcome.runIds),+ });+ }+ },+ [recordFor, addFiles],+ );++ return useMemo(+ () => ({+ stateFor,+ recordFor: recordSummaryFor,+ enabledFolderIds,+ anyEnabled,+ listActiveRuns,+ listFiles,+ retryFile,+ revertFile,+ revertAll,+ enable,+ disable,+ remove,+ sweep,+ }),+ [+ stateFor,+ recordSummaryFor,+ enabledFolderIds,+ anyEnabled,+ listActiveRuns,+ listFiles,+ retryFile,+ revertFile,+ revertAll,+ enable,+ disable,+ remove,+ sweep,+ ],+ );+}++/** Reload the shared list — for a caller that created a folder outside these actions. */+export function refreshProcessingFolders(): Promise<void> {+ return load(true);+}diff --git a/frontend/editor/src/proprietary/policies/catalog.ts b/frontend/editor/src/proprietary/policies/catalog.tsnew file mode 100644index 0000000000..a8e31f14f1--- /dev/null+++ b/frontend/editor/src/proprietary/policies/catalog.ts@@ -0,0 +1,356 @@+/**+ * The policy/pipeline catalogue. One catalogue, two lenses: the portal's Pipelines gallery+ * and the editor's folder-processing setup both read it.+ */++import { policyStep, type PolicyToolStep } from "@app/policies/operations";+import type { ToolEndpoint } from "@app/types/toolApiTypes";+import type { WirePipelineStep } from "@app/policies/types";++export type { WirePipelineStep as PipelineStep } from "@app/policies/types";++export type PolicyStatus = "active" | "paused";++export type PolicyFieldType = "toggle" | "select" | "chips" | "text";++export interface PolicyField {+ label: string;+ key: string;+ type: PolicyFieldType;+ value: boolean | string | string[];+ options?: string[];+}++export interface PolicyCategory {+ id: string;+ label: string;+ tone: "neutral" | "blue" | "purple" | "green" | "amber" | "red";+ desc: string;+ providesClassification?: boolean;+ comingSoon?: boolean;+ requiresAiEngine?: boolean;+}++export interface PolicyConfigDef {+ summary: string;+ rules: string[];+ scopeLabel: string;+ fields: PolicyField[];+ defaultOperations: PolicyToolStep[];+}++export interface PolicyState {+ configured: boolean;+ status: PolicyStatus;+ /** A policy rather than an ordinary pipeline (see `Policy.required`). */+ required: boolean;+ name?: string;+ icon?: string;+ /** Options the wizard doesn't model, preserved so a wizard save round-trips them (see codec). */+ extraOptions?: Record<string, unknown>;+ sources: string[];+ /** Whether the editor runs this policy per file; stored, not derived from `sources`. */+ runsOnEditor?: boolean;+ scopeTypes: string[];+ reviewerEmail: string;+ fieldValues: Record<string, boolean | string | string[]>;+ outputMode?: "new_file" | "new_version";+ outputName?: string;+ outputNamePosition?: "prefix" | "suffix" | "auto-number";+ runOn?: "upload" | "export";+ maxRetries?: number;+ retryDelayMinutes?: number;+ backendId?: string;+ isDefault?: boolean;+}++export interface PolicySetupResult {+ required: boolean;+ /** Stored options the wizard doesn't model, carried through so a save preserves them (see codec). */+ extraOptions?: Record<string, unknown>;+ fieldValues: Record<string, boolean | string | string[]>;+ sources: string[];+ runsOnEditor: boolean;+ scopeTypes: string[];+ reviewerEmail: string;+ outputMode: "new_file" | "new_version";+ outputName: string;+ outputNamePosition: "prefix" | "suffix" | "auto-number";+ runOn: "upload" | "export";+ maxRetries: number;+ retryDelayMinutes: number;+ steps: WirePipelineStep[];+}++export interface DecoratedPolicy {+ category: PolicyCategory;+ config: PolicyConfigDef;+ state: PolicyState;+ steps: WirePipelineStep[];+ stats: import("@app/policies/types").PolicyStats;+ activity: import("@app/policies/types").PolicyActivityItem[];+}++export interface PoliciesResponse {+ catalogue: CatalogueEntry[];+}++export interface CatalogueEntry {+ category: PolicyCategory;+ config: PolicyConfigDef;+ policy: DecoratedPolicy | null;+}++const ENDPOINT_LABELS: Partial<+ Record<ToolEndpoint | "/api/v1/ai/tools/classify-and-label", string>+> = {+ "/api/v1/security/auto-redact": "portal.policies.endpoints.autoRedact",+ "/api/v1/security/sanitize-pdf": "portal.policies.endpoints.sanitizePdf",+ "/api/v1/security/add-watermark": "portal.policies.endpoints.addWatermark",+ "/api/v1/misc/ocr-pdf": "portal.policies.endpoints.ocrPdf",+ "/api/v1/misc/flatten": "portal.policies.endpoints.flatten",+ "/api/v1/misc/compress-pdf": "portal.policies.endpoints.compressPdf",+ "/api/v1/ai/tools/classify-and-label":+ "portal.policies.endpoints.classifyAndLabel",+};++export function humanizeEndpoint(+ path: string,+ t: (key: string) => string,+): string {+ const label = ENDPOINT_LABELS[path as ToolEndpoint];+ if (label) return t(label);+ const last = path.split("/").filter(Boolean).pop() ?? path;+ return last+ .replace(/-/g, " ")+ .replace(/\b\w/g, (c) => c.toUpperCase())+ .trim();+}++const DEFAULT_PII_PATTERNS: string[] = [+ "\\b(?!000|666|9\\d{2})\\d{3}([- ])(?!00)\\d{2}\\1(?!0000)\\d{4}\\b",+ "\\b(?:4\\d{12}(?:\\d{3})?|5[1-5]\\d{14}|3[47]\\d{13}|6(?:011|5\\d{2})\\d{12})\\b",+];++export const POLICY_CATEGORIES: PolicyCategory[] = [+ {+ id: "ingestion",+ label: "portal.policies.categories.ingestion.label",+ tone: "blue",+ desc: "portal.policies.categories.ingestion.desc",+ providesClassification: true,+ comingSoon: true,+ },+ {+ id: "security",+ label: "portal.policies.categories.security.label",+ tone: "purple",+ desc: "portal.policies.categories.security.desc",+ },+ {+ id: "classification",+ label: "portal.policies.categories.classification.label",+ tone: "blue",+ desc: "portal.policies.categories.classification.desc",+ providesClassification: true,+ },+ {+ id: "compliance",+ label: "portal.policies.categories.compliance.label",+ tone: "amber",+ desc: "portal.policies.categories.compliance.desc",+ comingSoon: true,+ },+ {+ id: "routing",+ label: "portal.policies.categories.routing.label",+ tone: "green",+ desc: "portal.policies.categories.routing.desc",+ comingSoon: true,+ },+ {+ id: "retention",+ label: "portal.policies.categories.retention.label",+ tone: "neutral",+ desc: "portal.policies.categories.retention.desc",+ comingSoon: true,+ },+];++export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {+ ingestion: {+ summary: "portal.policies.config.ingestion.summary",+ rules: [+ "portal.policies.config.ingestion.rules.0",+ "portal.policies.config.ingestion.rules.1",+ "portal.policies.config.ingestion.rules.2",+ "portal.policies.config.ingestion.rules.3",+ ],+ scopeLabel: "portal.policies.config.scopeAll",+ defaultOperations: [policyStep("ocr"), policyStep("flatten")],+ fields: [+ {+ label: "portal.policies.config.ingestion.fields.minConfidence",+ key: "minConfidence",+ type: "select",+ value: "p80",+ options: ["p60", "p70", "p80", "p90", "p95"],+ },+ {+ label: "portal.policies.config.ingestion.fields.belowThreshold",+ key: "belowThreshold",+ type: "select",+ value: "flagForReview",+ options: ["flagForReview", "routeToBucket", "hold"],+ },+ ],+ },+ security: {+ summary: "portal.policies.config.security.summary",+ rules: [+ "portal.policies.config.security.rules.0",+ "portal.policies.config.security.rules.1",+ "portal.policies.config.security.rules.2",+ ],+ scopeLabel: "portal.policies.config.scopeAll",+ defaultOperations: [+ // Flatten to image so redactions can't be lifted off.+ policyStep("redact", {+ useRegex: true,+ convertPDFToImage: true,+ wordsToRedact: DEFAULT_PII_PATTERNS,+ }),+ // JavaScript removal only; the tool enables removeEmbeddedFiles by default, so turn it off.+ policyStep("sanitize", { removeEmbeddedFiles: false }),+ // Bake in via image so it can't be stripped.+ policyStep("watermark", { convertPDFToImage: true }),+ ],+ fields: [],+ },+ classification: {+ summary: "portal.policies.config.classification.summary",+ rules: [+ "portal.policies.config.classification.rules.0",+ "portal.policies.config.classification.rules.1",+ ],+ scopeLabel: "portal.policies.config.scopeAll",+ defaultOperations: [policyStep("classify")],+ fields: [],+ },+ compliance: {+ summary: "portal.policies.config.compliance.summary",+ rules: [+ "portal.policies.config.compliance.rules.0",+ "portal.policies.config.compliance.rules.1",+ "portal.policies.config.compliance.rules.2",+ ],+ scopeLabel: "portal.policies.config.scopeAll",+ defaultOperations: [+ policyStep("sanitize"),+ policyStep("flatten"),+ policyStep("purviewApplyLabel"),+ ],+ fields: [+ {+ label: "portal.policies.config.compliance.fields.frameworks",+ key: "frameworks",+ type: "chips",+ value: ["hipaa"],+ options: ["hipaa", "gdpr", "soc2", "fedramp", "pciDss", "iso27001"],+ },+ {+ label: "portal.policies.config.compliance.fields.onViolation",+ key: "onViolation",+ type: "select",+ value: "flagForReview",+ options: [+ "flagForReview",+ "blockExport",+ "autoRedactPhi",+ "quarantineDocument",+ ],+ },+ {+ label: "portal.policies.config.compliance.fields.auditTrail",+ key: "auditTrail",+ type: "toggle",+ value: true,+ },+ {+ label: "portal.policies.config.compliance.fields.accessLog",+ key: "accessLog",+ type: "toggle",+ value: true,+ },+ ],+ },+ routing: {+ summary: "portal.policies.config.routing.summary",+ rules: [+ "portal.policies.config.routing.rules.0",+ "portal.policies.config.routing.rules.1",+ "portal.policies.config.routing.rules.2",+ ],+ scopeLabel: "portal.policies.config.scopeAll",+ defaultOperations: [policyStep("compress")],+ fields: [+ {+ label: "portal.policies.config.routing.fields.destination",+ key: "destination",+ type: "select",+ value: "documents",+ options: ["documents", "s3Bucket", "sharePoint", "webhook"],+ },+ {+ label: "portal.policies.config.routing.fields.webhookUrl",+ key: "webhookUrl",+ type: "text",+ value: "",+ },+ {+ label: "portal.policies.config.routing.fields.notify",+ key: "notify",+ type: "toggle",+ value: false,+ },+ ],+ },+ retention: {+ summary: "portal.policies.config.retention.summary",+ rules: [+ "portal.policies.config.retention.rules.0",+ "portal.policies.config.retention.rules.1",+ "portal.policies.config.retention.rules.2",+ ],+ scopeLabel: "portal.policies.config.scopeAll",+ defaultOperations: [policyStep("compress")],+ fields: [+ {+ label: "portal.policies.config.retention.fields.keepFor",+ key: "keepFor",+ type: "select",+ value: "sevenYears",+ options: [+ "thirtyDays",+ "oneYear",+ "threeYears",+ "sevenYears",+ "indefinite",+ ],+ },+ {+ label: "portal.policies.config.retention.fields.archiveAfter",+ key: "archiveAfter",+ type: "select",+ value: "never",+ options: ["thirtyDays", "ninetyDays", "oneYear", "never"],+ },+ {+ label: "portal.policies.config.retention.fields.immutableHold",+ key: "immutableHold",+ type: "toggle",+ value: false,+ },+ ],+ },+};diff --git a/frontend/editor/src/proprietary/services/processingFolderApi.ts b/frontend/editor/src/proprietary/services/processingFolderApi.tsnew file mode 100644index 0000000000..b240ffaa0e--- /dev/null+++ b/frontend/editor/src/proprietary/services/processingFolderApi.ts@@ -0,0 +1,230 @@+/**+ * Client for `/api/v1/processing-folders`: a folder with a pipeline attached.+ * The backend composes the source + policy pair behind the route.+ */++import apiClient from "@app/services/apiClient";+import { readDiskFile } from "@app/services/localFolderContents";++/** The classify step: identifies the document's type and tags it. No parameters. */+export const CLASSIFY_OPERATION = "/api/v1/ai/tools/classify-and-label";++export interface ProcessingFolderStep {+ operation: string;+ parameters: Record<string, unknown>;+ assets?: Record<string, unknown>;+}++export interface ProcessingFolder {+ id: string;+ /** Set for a storage-backed folder; null when the folder is mounted from disk. */+ folderId: string | null;+ /** Set for a disk-backed (mounted) folder; null when it is storage-backed. */+ directory: string | null;+ name: string;+ enabled: boolean;+ steps: ProcessingFolderStep[];+ output: Record<string, unknown>;+}++/** Exactly one of `folderId` (app storage) or `directory` (server-disk path) says where a+ * folder watches. */+export interface SaveProcessingFolderRequest {+ id?: string | null;+ folderId?: string;+ directory?: string;+ enabled?: boolean;+ steps: ProcessingFolderStep[];+ output?: Record<string, unknown>;+}++/** Every processing folder the current user owns. */+export async function fetchProcessingFolders(): Promise<ProcessingFolder[]> {+ const res = await apiClient.get<ProcessingFolder[]>(+ "/api/v1/processing-folders",+ );+ return res.data ?? [];+}++/** Create or update one; creating sweeps the existing backlog behind the response. */+export async function saveProcessingFolder(+ request: SaveProcessingFolderRequest,+): Promise<ProcessingFolder> {+ const res = await apiClient.post<ProcessingFolder>(+ "/api/v1/processing-folders",+ request,+ );+ return res.data;+}++export interface SweepOutcome {+ runIds: string[];+ filesListed: number;+ alreadyProcessed: number;+ /** Files skipped because an earlier run failed on them and they stayed parked. */+ parked: number;+ /** Files the sweep took on again after an earlier failure. */+ retried: number;+}++export async function sweepProcessingFolder(id: string): Promise<SweepOutcome> {+ const res = await apiClient.post<SweepOutcome>(+ `/api/v1/processing-folders/${id}/sweep`,+ );+ return res.data;+}++/** Cancel the folder's in-flight runs; cancelled files return to queued. */+export async function cancelProcessingRuns(id: string): Promise<void> {+ await apiClient.post(`/api/v1/processing-folders/${id}/runs/cancel`);+}++/** Remove the processing behaviour. The folder and its files are untouched. */+export async function deleteProcessingFolder(id: string): Promise<void> {+ await apiClient.delete(`/api/v1/processing-folders/${id}`);+}++/** The default pipeline: classification. Outputs replace the file in place. */+export function classificationDefaults(+ folderId: string,+): SaveProcessingFolderRequest {+ return {+ folderId,+ enabled: true,+ steps: [{ operation: CLASSIFY_OPERATION, parameters: {}, assets: {} }],+ output: { mode: "new_version" },+ };+}++export interface DownloadsSuggestion {+ directory: string;+ available: boolean;+ pdfCount: number;+ limit: number;+}++/** The server's Downloads path and PDF count — the browser cannot see machine paths. */+export async function fetchDownloadsSuggestion(): Promise<DownloadsSuggestion> {+ const res = await apiClient.get<DownloadsSuggestion>(+ "/api/v1/processing-folders/downloads-suggestion",+ );+ return res.data;+}++/** One file a run produced. Downloadable by id from the general files endpoint. */+export interface ProcessingRunOutput {+ fileId: string;+ fileName?: string | null;+}++export interface ProcessingFolderRun {+ runId?: string;+ status: string;+ error?: string | null;+ outputs?: ProcessingRunOutput[] | null;+ /** The input document's display name, for runs whose source recorded one. */+ fileName?: string | null;+ currentStep?: number;+ stepCount?: number;+}++/** Runs belonging to a processing folder, newest first — drives the progress display. */+export async function fetchProcessingFolderRuns(+ policyId: string,+): Promise<ProcessingFolderRun[]> {+ // Filtered server-side (this polls every second); the client-side filter guards+ // against a backend that ignores the parameter.+ const res = await apiClient.get<+ (ProcessingFolderRun & { policyId?: string })[]+ >("/api/v1/policies/runs", { params: { policyId } });+ return (res.data ?? []).filter((run) => run.policyId === policyId);+}++/** An absolute filesystem path (Windows drive-letter or POSIX rooted). */+function isAbsolutePath(value: string): boolean {+ return /^([A-Za-z]:[\\/]|\/)/.test(value);+}++/**+ * Fetch a run output's bytes as a File. A storage-backed run's `fileId` is a stored-file id+ * (the job-files endpoint rejects it — same field name, different id space). A disk-backed+ * run's `fileId` is synthetic and `fileName` is an absolute output path, readable only where+ * the build can see the filesystem (desktop).+ */+export async function fetchRunOutputFile(+ output: ProcessingRunOutput,+): Promise<File> {+ const name = output.fileName?.trim() || `${output.fileId}.pdf`;+ if (isAbsolutePath(name)) {+ const baseName = name.split(/[\\/]/).pop() || name;+ const file = await readDiskFile({+ path: name,+ name: baseName,+ sizeBytes: 0,+ lastModified: 0,+ });+ if (!file) {+ throw new Error(`This build cannot read the run output at ${name}`);+ }+ return file;+ }+ const res = await apiClient.get(+ `/api/v1/storage/files/${output.fileId}/download`,+ { responseType: "blob" },+ );+ return new File([res.data as Blob], name, {+ type: (res.data as Blob).type || "application/pdf",+ });+}++export interface MountedFile {+ name: string;+ sizeBytes: number;+ lastModified: number;+ /** Its place in the folder's pipeline: done, processing, failed, or waiting. */+ state: "done" | "processing" | "failed" | "waiting";+ hasOriginal?: boolean;+}++export async function fetchMountedFiles(id: string): Promise<MountedFile[]> {+ const res = await apiClient.get<MountedFile[]>(+ `/api/v1/processing-folders/${id}/files`,+ );+ return res.data ?? [];+}++/** Retry one failed file now; every other parked failure stays parked. */+export async function retryMountedFile(+ id: string,+ name: string,+): Promise<void> {+ await apiClient.post(`/api/v1/processing-folders/${id}/files/retry`, {+ name,+ });+}++/** Restore a file's archived original, discarding its processed version. */+export async function revertMountedFile(+ id: string,+ name: string,+): Promise<void> {+ await apiClient.post(`/api/v1/processing-folders/${id}/files/revert`, {+ name,+ });+}++/** Outcome of a folder-wide restore: originals brought back, files left as-is. */+export interface RevertAllOutcome {+ restored: number;+ skipped: number;+}++/** Restore every archived original at once; files mid-run are skipped, not raced. */+export async function revertAllMountedFiles(+ id: string,+): Promise<RevertAllOutcome> {+ const res = await apiClient.post<RevertAllOutcome>(+ `/api/v1/processing-folders/${id}/files/revert-all`,+ );+ return res.data;+}diff --git a/frontend/editor/src/proprietary/services/processingRunDelivery.test.ts b/frontend/editor/src/proprietary/services/processingRunDelivery.test.tsnew file mode 100644index 0000000000..ef1fe00798--- /dev/null+++ b/frontend/editor/src/proprietary/services/processingRunDelivery.test.ts@@ -0,0 +1,119 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++const fetchRuns = vi.fn();+const fetchOutput = vi.fn();+vi.mock("@app/services/processingFolderApi", () => ({+ fetchProcessingFolderRuns: (policyId: string) => fetchRuns(policyId),+ fetchRunOutputFile: (output: unknown) => fetchOutput(output),+}));++import { deliverSweepResults } from "@app/services/processingRunDelivery";++/** A settled run with one output, in the shape the runs feed returns. */+const completedRun = (runId: string) => ({+ runId,+ status: "COMPLETED",+ fileName: `${runId}.pdf`,+ outputs: [{ fileId: `${runId}-out`, fileName: `${runId}.pdf` }],+});++// The loop only checks the fetched File is non-null, so a light stub avoids a+// File/Blob dependency on the test environment.+const fileFor = (name: string) => ({ name }) as unknown as File;++describe("deliverSweepResults - one live delivery per folder", () => {+ beforeEach(() => {+ fetchRuns.mockReset();+ fetchOutput.mockReset();+ fetchRuns.mockResolvedValue([completedRun("r1")]);+ fetchOutput.mockResolvedValue(fileFor("r1.pdf"));+ });++ it("joins a delivery already running for the same folder rather than starting a second", async () => {+ const addFiles = vi.fn().mockResolvedValue(undefined);++ const first = deliverSweepResults("policy-1", 1, addFiles);+ const second = deliverSweepResults("policy-1", 1, addFiles);++ // Both callers ride one loop, so the run's outputs open once, not once per caller.+ expect(second).toBe(first);+ await Promise.all([first, second]);+ expect(addFiles).toHaveBeenCalledTimes(1);+ });++ it("starts a fresh delivery once the previous one for that folder has finished", async () => {+ const addFiles = vi.fn().mockResolvedValue(undefined);++ await deliverSweepResults("policy-1", 1, addFiles);+ // Registry cleared on completion: this is a new loop, not the resolved promise.+ await deliverSweepResults("policy-1", 1, addFiles);++ expect(addFiles).toHaveBeenCalledTimes(2);+ });++ it("does not join a callback-bearing caller, so its callbacks still fire", async () => {+ const addFiles = vi.fn().mockResolvedValue(undefined);+ const onProgress = vi.fn();++ // A caller that needs progress (the wizard) must run its own loop rather than+ // join the callback-less one already running, which cannot fire its callbacks.+ const bare = deliverSweepResults("policy-1", 1, addFiles);+ const withCallbacks = deliverSweepResults("policy-1", 1, addFiles, {+ onProgress,+ });++ expect(withCallbacks).not.toBe(bare);+ await Promise.all([bare, withCallbacks]);+ expect(onProgress).toHaveBeenCalled();+ // Its own loop, but not its own copy of the results.+ expect(addFiles).toHaveBeenCalledTimes(1);+ });++ it("opens a run once when a resume's delivery and a sweep's overlap", async () => {+ const opened: string[] = [];+ const addFiles = vi.fn().mockImplementation(async (files: File[]) => {+ files.forEach((file) => opened.push(file.name));+ });++ // useProcessingFolders: enable() runs callback-less, sweep() always passes+ // includeRunIds - so the sweep runs its own loop over the same settled run.+ const fromEnable = deliverSweepResults("policy-1", null, addFiles);+ const fromSweep = deliverSweepResults("policy-1", 1, addFiles, {+ includeRunIds: new Set(["r1"]),+ });+ await Promise.all([fromEnable, fromSweep]);++ expect(opened).toEqual(["r1.pdf"]);+ });++ it("still reports a run to every loop's onSettled, opened by it or not", async () => {+ const addFiles = vi.fn().mockResolvedValue(undefined);+ const onSettled = vi.fn();++ const bare = deliverSweepResults("policy-1", 1, addFiles);+ const watcher = deliverSweepResults("policy-1", 1, addFiles, { onSettled });+ await Promise.all([bare, watcher]);++ // The wizard reads the result's classification labels off these files, so a+ // joined-away run must still arrive with its outputs attached.+ expect(onSettled).toHaveBeenCalledTimes(1);+ expect(onSettled.mock.calls[0][0].files).toHaveLength(1);+ });++ it("delivers distinct folders in parallel - the guard is keyed per folder", async () => {+ fetchRuns.mockImplementation((policyId: string) =>+ Promise.resolve([completedRun(policyId)]),+ );+ fetchOutput.mockImplementation((output: { fileName: string }) =>+ Promise.resolve(fileFor(output.fileName)),+ );+ const addFiles = vi.fn().mockResolvedValue(undefined);++ const a = deliverSweepResults("policy-a", 1, addFiles);+ const b = deliverSweepResults("policy-b", 1, addFiles);++ expect(b).not.toBe(a);+ await Promise.all([a, b]);+ expect(addFiles).toHaveBeenCalledTimes(2);+ });+});diff --git a/frontend/editor/src/proprietary/services/processingRunDelivery.ts b/frontend/editor/src/proprietary/services/processingRunDelivery.tsnew file mode 100644index 0000000000..e23751c76f--- /dev/null+++ b/frontend/editor/src/proprietary/services/processingRunDelivery.ts@@ -0,0 +1,331 @@+/**+ * Delivers a sweep's results into the workbench, opening each run's results as it settles:+ * waiting for the whole sweep would hold everything behind the slowest file.+ */++import {+ fetchProcessingFolderRuns,+ fetchRunOutputFile,+ type ProcessingFolderRun,+ type ProcessingRunOutput,+} from "@app/services/processingFolderApi";++const TERMINAL = ["COMPLETED", "FAILED", "CANCELLED"];+/** Fast polls first — the earliest finishes land within seconds — then a steady 1s,+ * budgeted to ~15 minutes overall. */+const FAST_POLL_MS = 400;+const FAST_POLLS = 25;+const POLL_MS = 1000;+const MAX_POLLS = 925;+/** Result downloads run a few at a time: parallel enough to keep up with a burst+ * of finishes, bounded so a hundred results don't open a hundred requests. */+const FETCH_CONCURRENCY = 4;+/** With no expected count, polls with zero runs before concluding nothing started. */+const NO_RUN_GRACE_POLLS = 20;++export interface SweepDeliveryProgress {+ /** Runs that completed successfully so far. */+ processed: number;+ /** Runs that failed or were cancelled so far. */+ failed: number;+ /** Result files opened into the workbench so far. */+ opened: number;+ /** True when the budget ran out with runs still unsettled. */+ stalled: boolean;+}++export interface RunSettlement {+ runId: string;+ /** The input document's display name, when the run's source recorded one. */+ fileName: string | null;+ failed: boolean;+ files: File[];+}++export interface SweepDeliveryCallbacks {+ /** Called after every poll with cumulative counts. */+ onProgress?: (progress: SweepDeliveryProgress) => void;+ /** Called after every poll with the folder's raw runs — live per-file state. */+ onRuns?: (runs: ProcessingFolderRun[]) => void;+ /** Called once per run as it settles, with the files opened for it. */+ onSettled?: (settlement: RunSettlement) => void;+ /** Polled each cycle; true stops the loop quietly (the caller cancelled). */+ isCancelled?: () => boolean;+ /** Runs to ignore entirely — a baseline captured before the sweep was triggered. */+ excludeRunIds?: ReadonlySet<string>;+ /** When set, only these runs count; everything else in the feed is ignored. */+ includeRunIds?: ReadonlySet<string>;+}++/** The folder's current run ids — captured before a sweep so its delivery can ignore them. */+export async function currentRunIds(+ policyId: string,+): Promise<ReadonlySet<string>> {+ const runs = await fetchProcessingFolderRuns(policyId).catch(() => []);+ return new Set(+ runs.map((run) => run.runId).filter((id): id is string => id != null),+ );+}++const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/** Map with a bounded number of in-flight promises; failed items resolve null. */+async function mapBounded<T, R>(+ items: T[],+ limit: number,+ fn: (item: T) => Promise<R>,+): Promise<(R | null)[]> {+ const results: (R | null)[] = new Array(items.length).fill(null);+ let next = 0;+ const workers = Array.from(+ { length: Math.min(limit, items.length) },+ async () => {+ while (next < items.length) {+ const index = next++;+ try {+ results[index] = await fn(items[index]);+ } catch (e) {+ // Logged rather than swallowed: a fetch failing for every file looks like+ // the feature simply not working.+ console.warn("[processing folders] could not open a result", e);+ }+ }+ },+ );+ await Promise.all(workers);+ return results;+}++/**+ * In-flight delivery per policy id. A second callback-less trigger for a folder joins the+ * running loop rather than starting its own.+ */+const deliveriesInFlight = new Map<string, Promise<SweepDeliveryProgress>>();++/**+ * Runs whose outputs are already in the workbench, per folder, held while any delivery for that+ * folder is live. Two deliveries for one folder overlap by design (a caller passing callbacks+ * must run its own loop to receive them) and both see the same settled run; the workbench+ * cannot dedup the result away, because a disk output File has no stable lastModified, so its+ * `name|size|lastModified` key differs on each fetch. Callbacks fire for both loops; only the+ * opening is claimed once.+ */+const openedRuns = new Map<string, Set<string>>();++/** Live deliveries per folder; the last one out releases that folder's opened set. */+const liveDeliveries = new Map<string, number>();++function enterDelivery(policyId: string): void {+ liveDeliveries.set(policyId, (liveDeliveries.get(policyId) ?? 0) + 1);+}++function leaveDelivery(policyId: string): void {+ const remaining = (liveDeliveries.get(policyId) ?? 1) - 1;+ if (remaining > 0) {+ liveDeliveries.set(policyId, remaining);+ return;+ }+ // Released with the last delivery, so a later sweep of the same folder is free to+ // open its results again rather than being suppressed by a stale set.+ liveDeliveries.delete(policyId);+ openedRuns.delete(policyId);+}++function claimRunForOpening(policyId: string, runId: string): boolean {+ let opened = openedRuns.get(policyId);+ if (!opened) {+ opened = new Set();+ openedRuns.set(policyId, opened);+ }+ if (opened.has(runId)) {+ return false;+ }+ opened.add(runId);+ return true;+}++/**+ * Poll `policyId`'s runs until they settle, opening each completed run's outputs into the+ * workbench via `addFiles`. A numeric `expected` stops there; `null` is for callers with no+ * count yet (the sweep runs behind the create response) and stops once every observed run is+ * terminal and stable, or after a grace period with no runs.+ *+ * A callback-less caller joins a delivery already running for the folder ({@link+ * deliveriesInFlight}); one that passes callbacks runs its own, so its callbacks always fire.+ */+export function deliverSweepResults(+ policyId: string,+ expected: number | null,+ addFiles: (+ files: File[],+ options?: { selectFiles?: boolean },+ ) => Promise<unknown>,+ callbacks?:+ | SweepDeliveryCallbacks+ | ((progress: SweepDeliveryProgress) => void),+): Promise<SweepDeliveryProgress> {+ if (callbacks) {+ return deliverSweepResultsUntracked(+ policyId,+ expected,+ addFiles,+ callbacks,+ );+ }+ const running = deliveriesInFlight.get(policyId);+ if (running) {+ return running;+ }+ const started = deliverSweepResultsUntracked(+ policyId,+ expected,+ addFiles,+ ).finally(() => {+ if (deliveriesInFlight.get(policyId) === started) {+ deliveriesInFlight.delete(policyId);+ }+ });+ deliveriesInFlight.set(policyId, started);+ return started;+}++async function deliverSweepResultsUntracked(+ policyId: string,+ expected: number | null,+ addFiles: (+ files: File[],+ options?: { selectFiles?: boolean },+ ) => Promise<unknown>,+ callbacks?:+ | SweepDeliveryCallbacks+ | ((progress: SweepDeliveryProgress) => void),+): Promise<SweepDeliveryProgress> {+ enterDelivery(policyId);+ try {+ return await deliverSweepResultsLoop(+ policyId,+ expected,+ addFiles,+ callbacks,+ );+ } finally {+ leaveDelivery(policyId);+ }+}++async function deliverSweepResultsLoop(+ policyId: string,+ expected: number | null,+ addFiles: (+ files: File[],+ options?: { selectFiles?: boolean },+ ) => Promise<unknown>,+ callbacks?:+ | SweepDeliveryCallbacks+ | ((progress: SweepDeliveryProgress) => void),+): Promise<SweepDeliveryProgress> {+ const {+ onProgress,+ onRuns,+ onSettled,+ isCancelled,+ excludeRunIds,+ includeRunIds,+ } =+ typeof callbacks === "function"+ ? { onProgress: callbacks }+ : (callbacks ?? {});+ const alreadySettled = new Set<string>();+ let quietPolls = 0;+ let seenAnyRun = false;+ const progress: SweepDeliveryProgress = {+ processed: 0,+ failed: 0,+ opened: 0,+ stalled: false,+ };++ const fetchRunFiles = async (+ outputs: ProcessingRunOutput[],+ ): Promise<File[]> =>+ (await mapBounded(outputs, FETCH_CONCURRENCY, fetchRunOutputFile)).filter(+ (file): file is File => file !== null,+ );++ for (let attempt = 0; attempt < MAX_POLLS; attempt++) {+ if (isCancelled?.()) {+ return progress;+ }+ const fetched = await fetchProcessingFolderRuns(policyId).catch(() => []);+ // The registry retains finished runs for a while, so the feed can carry earlier+ // sweeps' history; unscoped, an old run would re-deliver its results and the stop+ // conditions would fire against work this call never started.+ const runs = fetched.filter((run) =>+ includeRunIds+ ? run.runId != null && includeRunIds.has(run.runId)+ : !(run.runId != null && excludeRunIds?.has(run.runId)),+ );+ if (runs.length > 0) {+ seenAnyRun = true;+ }+ onRuns?.(runs);+ const settled = runs.filter((run) => TERMINAL.includes(run.status));+ const done = settled.filter((run) => run.status === "COMPLETED");+ progress.processed = done.length;+ progress.failed = settled.length - done.length;++ const fresh = settled.filter(+ (run) => run.runId && !alreadySettled.has(run.runId),+ );+ fresh.forEach((run) => alreadySettled.add(run.runId!));++ const opened: File[] = [];+ for (const run of fresh) {+ const failed = run.status !== "COMPLETED";+ const files = failed ? [] : await fetchRunFiles(run.outputs ?? []);+ // Fetched either way so this loop's onSettled still carries the result; only+ // the first delivery to claim the run puts it into the workbench.+ if (claimRunForOpening(policyId, run.runId!)) {+ opened.push(...files);+ }+ onSettled?.({+ runId: run.runId!,+ fileName: run.fileName ?? null,+ failed,+ files,+ });+ }+ if (+ expected == null &&+ !seenAnyRun &&+ runs.length === 0 &&+ attempt >= NO_RUN_GRACE_POLLS+ ) {+ // Nothing ever started: the sweep found no claimable files.+ onProgress?.({ ...progress });+ return progress;+ }+ if (opened.length > 0) {+ // One addFiles per poll batch, never selecting: a selection isn't meaningful+ // across a folderful of results.+ await addFiles(opened);+ progress.opened += opened.length;+ }+ onProgress?.({ ...progress });++ if (expected != null) {+ if (settled.length >= expected) return progress;+ } else if (runs.length > 0 && settled.length === runs.length) {+ quietPolls += 1;+ // Two stable all-terminal polls: a sweep still claiming would have shown+ // a new run by now.+ if (quietPolls >= 2) return progress;+ } else {+ quietPolls = 0;+ }+ await delay(attempt < FAST_POLLS ? FAST_POLL_MS : POLL_MS);+ }+ progress.stalled = true;+ onProgress?.({ ...progress });+ return progress;+}