#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
Show when smart folder processing fails (#8085)
EthanHealy0123209c9a7271
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionException.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionException.javaindex bd0ed2d001..274a5dfafd 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionException.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionException.java@@ -25,9 +25,20 @@ public class FailureActionException extends RuntimeException {/** Offered, but the client is what runs it, so refused rather than half-performed. */ACTION_NOT_DISPATCHABLE,+ /**+ * Declared and dispatchable, but aimed at an audience this caller is not in: a reviewer+ * reads a colleague's row without being able to act on the document behind it.+ */+ ACTION_NOT_THEIRS,/** The event is already closed, so no further transition is possible. */- ALREADY_CLOSED+ ALREADY_CLOSED,++ /**+ * Dispatched, but there was nothing to act on: the document is no longer parked as a+ * failure, or its folder yielded no run. The event stays open.+ */+ NOTHING_TO_RUN}private final Reason reason;@@ -50,7 +61,9 @@ public class FailureActionException extends RuntimeException {case EVENT_NOT_FOUND -> HttpStatus.NOT_FOUND;case ACTION_NOT_RECOGNISED, ACTION_NOT_DECLARED, ACTION_NOT_DISPATCHABLE ->HttpStatus.BAD_REQUEST;- case ALREADY_CLOSED -> HttpStatus.CONFLICT;+ // Not a 404: the caller may legitimately read the row, they just may not do this.+ case ACTION_NOT_THEIRS -> HttpStatus.FORBIDDEN;+ case ALREADY_CLOSED, NOTHING_TO_RUN -> HttpStatus.CONFLICT;};}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.javaindex 2a4a5f4090..7192dd5f7a 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java@@ -9,7 +9,6 @@ import lombok.Getter;*/@Getterpublic enum FailureActionId {-/*** Kept in the vocabulary for as long as any persisted row is {@code ACKNOWLEDGED}: such rows* must stay readable and closable whether or not any kind currently offers this.@@ -18,13 +17,16 @@ public enum FailureActionId {DISMISS(Execution.SERVER, "Dismiss"),- /** Opens the failed tool with its document, rather than running it again unattended. */- OPEN_IN_TOOL(Execution.CLIENT, "Retry"),+ /**+ * Runs the failed step again. A browser holding the document opens the tool with it loaded; a+ * smart folder's document is re-run by the server, the only side that can reach it.+ */+ OPEN_IN_TOOL(Execution.EITHER, "Retry"),- /** Unlocks the document with a password the owner supplies. */+ /** Unlocks the document with a password the owner supplies, then re-runs. */DECRYPT(Execution.CLIENT, "Unlock"),- /** Repairs the document in the owner's client, then re-runs. */+ /** Repairs the document, then re-runs. */REPAIR(Execution.CLIENT, "Repair"),/** Open the document behind the incident, in whichever client can resolve its id. */@@ -32,7 +34,7 @@ public enum FailureActionId {VIEW_IN_PROCESSOR(Execution.CLIENT, "View in processor");- /** Dispatch refuses a {@code CLIENT} id, so this is enforced rather than merely documented. */+ /** Dispatch refuses an id that does not run on the server, so this is enforced. */public enum Execution {/** {@link FailureActionRegistry} requires a {@link FailureAction} bean for these. */@@ -41,7 +43,13 @@ public enum FailureActionId {/*** Declared and rendered, never dispatched: the server has neither the file nor the tool.*/- CLIENT+ CLIENT,++ /**+ * Per row, not declared here: a reader holding the file acts on it themselves; a document+ * only the server can reach is acted on there. See {@link #executionFor(boolean)}.+ */+ EITHER}private final Execution execution;@@ -54,8 +62,19 @@ public enum FailureActionId {this.defaultLabel = defaultLabel;}- /** Also whether it can be dispatched. */- public boolean runsOnServer() {- return execution == Execution.SERVER;+ /**+ * Where this action runs for a document in the given place, which is what the client is told+ * and what dispatch is checked against. Only {@link Execution#EITHER} depends on the argument.+ */+ public Execution executionFor(boolean inSmartFolder) {+ if (execution != Execution.EITHER) {+ return execution;+ }+ return inSmartFolder ? Execution.SERVER : Execution.CLIENT;+ }++ /** Whether a handler bean must exist: true for anything that can ever be dispatched. */+ public boolean canRunOnServer() {+ return execution != Execution.CLIENT;}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionRegistry.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionRegistry.javaindex dad1bd5eda..ffdda17ef6 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionRegistry.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionRegistry.java@@ -17,8 +17,8 @@ import lombok.extern.slf4j.Slf4j;* point: because kinds declare action ids as data, one could name an action nobody implements,* which would otherwise show up as a button that 400s rather than as a failed boot.*- * <p>Only {@link FailureActionId.Execution#SERVER} ids belong here: a bean for a client action is- * refused, because dispatch could never reach it.+ * <p>Only ids the server can ever run belong here; a bean for a client-only action is refused. An+ * action the server runs for some documents still needs one, for the rows that reach it.*/@Slf4j@Service@@ -28,7 +28,7 @@ public class FailureActionRegistry {public FailureActionRegistry(List<FailureAction> actions) {for (FailureAction action : actions) {- if (!action.id().runsOnServer()) {+ if (!action.id().canRunOnServer()) {throw new IllegalStateException("Action "+ action.id()@@ -57,7 +57,7 @@ public class FailureActionRegistry {.flatMap(kind ->kind.getActions().stream()- .filter(FailureActionId::runsOnServer)+ .filter(FailureActionId::canRunOnServer).filter(action -> !byId.containsKey(action)).map(action -> kind.getId() + " -> " + action)).toList();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.javaindex e88a9f22b2..97465d3805 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java@@ -175,6 +175,22 @@ public enum FailureKind {global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, SECONDARY),global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),+ /**+ * A source could not be listed at all: a folder unplugged, renamed or locked down. Scoped to+ * the source, so a week-long outage is one incident. Claims no error code.+ */+ SOURCE_UNREADABLE(+ FailureStage.INPUT,+ FailureSeverity.ERROR,+ FailureRemedy.NEEDS_CONFIG_FIX,+ FailureScope.SOURCE,+ noErrorCodes(),+ fallback("This folder could not be read, so nothing in it was processed."),+ // No document to view: the sweep never got as far as one. Fixing it means fixing the+ // folder, which happens outside Stirling.+ global(VIEW_IN_PROCESSOR, OWNER, SECONDARY),+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),+/*** Ghostscript reached a page it could not draw, which its output names. Only that recognised* failure belongs here; the bucket Ghostscript output falls into otherwise is STEP_TOOL_FAILED.@@ -265,7 +281,7 @@ public enum FailureKind {noErrorCodes(),fallback("This run failed for a reason Stirling does not yet recognise."),// No known fix to declare, so a plain retry leads: these are often one-offs.- global(OPEN_IN_TOOL, OWNER, SECONDARY),+ resolution(OPEN_IN_TOOL, OWNER),global(VIEW_FILE, OWNER, SECONDARY),global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),global(DISMISS, ANYONE_WHO_SEES, OVERFLOW));diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventController.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventController.javaindex 07c992675f..1e3342cb20 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventController.java@@ -1,6 +1,7 @@package stirling.software.proprietary.failure;import java.util.Arrays;+import java.util.HashMap;import java.util.List;import java.util.Map;@@ -63,11 +64,13 @@ public class FileRunEventController {// and a leader the team's.int cappedLimit = Math.min(limit == null ? DEFAULT_LIMIT : Math.max(1, limit), MAX_LIMIT);+ // One policy lookup per distinct policy for the whole page, not one per row.+ Map<String, ProducingSurface> sources = new HashMap<>();List<FileRunEventView> events =// The kind filter is part of the query, before the limit is applied: filtering an// already-limited page could return nothing while matching rows exist.service.list(status, closed, kindId, cappedLimit).stream()- .map(event -> FileRunEventView.of(event, service.availableActions(event)))+ .map(event -> view(event, service.producingSurfaceOf(event, sources))).toList();return new FileRunEventsResponse(events);}@@ -89,7 +92,7 @@ public class FileRunEventController {Map<String, String> inputs = request == null ? Map.of() : request.safeInputs();try {FileRunEvent updated = service.dispatch(eventId, actionId, inputs);- return FileRunEventView.of(updated, service.availableActions(updated));+ return view(updated, service.producingSurfaceOf(updated));} catch (FailureActionException e) {throw new ResponseStatusException(FailureActionException.statusOf(e.getReason()), e.getMessage(), e);@@ -181,4 +184,8 @@ public class FileRunEventController {return inputs == null ? Map.of() : inputs;}}++ private FileRunEventView view(FileRunEvent event, ProducingSurface source) {+ return FileRunEventView.of(event, source, service.availableActions(event, source));+ }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventService.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventService.javaindex 17603fa601..0df86dc8d4 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventService.java@@ -3,6 +3,7 @@ package stirling.software.proprietary.failure;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;+import java.util.HashMap;import java.util.HexFormat;import java.util.List;import java.util.Map;@@ -15,6 +16,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.UserServiceInterface;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.store.PolicyStore;/*** Reads and acts on the incidents the calling user is allowed to see, which is where that decision@@ -46,6 +48,7 @@ public class FileRunEventService {private final PolicyManagementAuthority policyManagementAuthority;private final UserServiceInterface userService;private final ApplicationProperties applicationProperties;+ private final PolicyStore policyStore;/*** Record a failure a user hit in the editor. One incident per named file, so each document@@ -136,11 +139,7 @@ public class FileRunEventService {*/public FileRunEvent dispatch(String eventId, String actionId, Map<String, String> inputs) {// Whoever can see it can close it: a leader for the whole team, everyone else for the- // failures they caused. Someone who fixes their own problem should not have to ask a leader- // to clear the row.- //- // Audience decides what is offered, not what may be dispatched, so this scope is the whole- // gate. A server action aimed at OWNER alone would need its own guard here.+ // failures they caused. What each may then do is narrowed by audience below.FileRunEvent event = requireVisible(eventId);FailureActionId resolvedId = parseActionId(actionId);@@ -153,10 +152,21 @@ public class FileRunEventService {"Kind " + event.kind().getId() + " does not offer action " + resolvedId);}// Without this a client could post VIEW_FILE and be answered as though something happened.- if (!resolvedId.runsOnServer()) {+ // Resolved against this row: a retry of a document the browser holds is refused, not run.+ boolean inSmartFolder =+ FileRunEventView.DocumentLocation.of(event, producingSurfaceOf(event))+ == FileRunEventView.DocumentLocation.SMART_FOLDER;+ if (resolvedId.executionFor(inSmartFolder) != FailureActionId.Execution.SERVER) {throw new FailureActionException(FailureActionException.Reason.ACTION_NOT_DISPATCHABLE,- "Action " + resolvedId + " is run by the client, not the server");+ "Action " + resolvedId + " is run by the client for this document");+ }+ // Enforced here rather than per handler: reading a colleague's row is not a right to act+ // on the document behind it, and a handler that forgets to check is not the last line.+ if (!offeredToCaller(event, resolvedId)) {+ throw new FailureActionException(+ FailureActionException.Reason.ACTION_NOT_THEIRS,+ "Action " + resolvedId + " belongs to the owner of this failure");}if (event.status().terminal()) {throw new FailureActionException(@@ -217,6 +227,11 @@ public class FileRunEventService {* their audience is dropped, not disabled: greyed out would read as a permission problem.*/public List<AvailableAction> availableActions(FileRunEvent event) {+ return availableActions(event, producingSurfaceOf(event));+ }++ /** As {@link #availableActions(FileRunEvent)}, with the source already looked up. */+ public List<AvailableAction> availableActions(FileRunEvent event, ProducingSurface source) {Ownership ownership = ownershipOf(event);boolean reviewsTeam = reviewsTeam();boolean closed = event.status().terminal();@@ -224,23 +239,70 @@ public class FileRunEventService {// operator owns everything they can see.boolean unattended = enforced() && ownership == Ownership.UNOWNED;// Answered here, or the client reports "not on this device" about a document the row never- // identified in the first place.- boolean documentless = event.fileId() == null || event.fileId().isBlank();+ // named. A source-scoped row names none by design: the folder is the subject.+ boolean documentless =+ (event.fileId() == null || event.fileId().isBlank())+ && event.scope() != FailureScope.SOURCE;+ boolean inSmartFolder =+ FileRunEventView.DocumentLocation.of(event, source)+ == FileRunEventView.DocumentLocation.SMART_FOLDER;return event.kind().getOfferedActions().stream().filter(offer -> offeredTo(offer.audience(), ownership, reviewsTeam))- .map(offer -> availability(offer, closed, unattended, documentless))+ .map(offer -> availability(offer, inSmartFolder, closed, unattended, documentless)).toList();}+ /**+ * What produced the row, read from its policy rather than stored on it, so a converted folder+ * reads as what it is now. {@code cache} spares a list one lookup per row.+ */+ public ProducingSurface producingSurfaceOf(+ FileRunEvent event, Map<String, ProducingSurface> cache) {+ if (event.policyId() == null || event.policyId().isBlank()) {+ return ProducingSurface.EDITOR;+ }+ // A policy that has since been deleted still produced the row: POLICY, not EDITOR, so the+ // client never tells the reader their own editor caused it.+ return cache.computeIfAbsent(+ event.policyId(),+ id ->+ policyStore+ .get(id)+ .map(ProducingSurface::of)+ .orElse(ProducingSurface.POLICY));+ }++ public ProducingSurface producingSurfaceOf(FileRunEvent event) {+ return producingSurfaceOf(event, new HashMap<>());+ }++ /**+ * Whether this caller is in the audience the kind declares for the action. Audience only: a+ * disabled offer stays dispatchable, since its reasons are about the row, not the caller.+ */+ private boolean offeredToCaller(FileRunEvent event, FailureActionId id) {+ Ownership ownership = ownershipOf(event);+ boolean reviewsTeam = reviewsTeam();+ return event.kind().getOfferedActions().stream()+ .filter(offer -> offer.id() == id)+ .anyMatch(offer -> offeredTo(offer.audience(), ownership, reviewsTeam));+ }+/** Enabled is derived from the reason, so a disabled button always has one to show. */private static AvailableAction availability(FailureKind.OfferedAction offer,+ boolean inSmartFolder,boolean closed,boolean unattended,boolean documentless) {String reason = disabledReasonFor(offer.audience(), closed, unattended, documentless);return new AvailableAction(- offer.id(), offer.labelKey(), offer.slot(), reason == null, reason);+ offer.id(),+ offer.labelKey(),+ offer.id().executionFor(inSmartFolder),+ offer.slot(),+ reason == null,+ reason);}/** Closed wins over everything, then the owner-only reasons, most specific first. */@@ -367,10 +429,14 @@ public class FileRunEventService {return applicationProperties.getSecurity().isEnableLogin();}- /** One action offered to one caller, availability resolved. */+ /**+ * One offer resolved for one caller and document. {@code execution} says which side runs this+ * row's copy, which for a retry follows the document.+ */public record AvailableAction(FailureActionId id,String labelKey,+ FailureActionId.Execution execution,FailureActionSlot slot,boolean enabled,String disabledReasonKey) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventView.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventView.javaindex 3b7501e9e2..103eecafe0 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventView.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FileRunEventView.java@@ -5,8 +5,10 @@ import java.util.List;/*** Wire shape of one incident. Carries i18n keys plus {@code defaultTitle} rather than rendered* copy, so the server can ship a new kind without a client release, and {@code actions} arrive- * already resolved so the client needs no rules. No document name: {@code fileId} is an opaque- * reference.+ * already resolved so the client needs no rules.+ *+ * <p>No document name, and no {@code fileId} on a source-fed row, whose identity is a path on the+ * operator's disk. See {@link #documentLocation}.*/public record FileRunEventView(String id,@@ -24,6 +26,8 @@ public record FileRunEventView(String runId,String sourceId,String fileId,+ /** Where the document is, decided by the server rather than inferred from the ids here. */+ DocumentLocation documentLocation,String actor,int occurrences,FileRunEventStatus status,@@ -32,9 +36,39 @@ public record FileRunEventView(long createdAt,long lastSeenAt) {+ /** Where the document behind an incident lives, which decides what can be offered for it. */+ public enum DocumentLocation {+ /** The reader's own browser minted the id, so client-side fixes can find it. */+ BROWSER,+ /** A folder the server watches. Only the server can reach it, and only for its owner. */+ SMART_FOLDER,+ /**+ * Nothing here can act on the document: the row names none, or a policy fed from a bucket+ * or a webhook named a file no browser holds and no folder action can address.+ */+ UNREACHABLE;++ /**+ * Fails closed on the source id: a source-fed row is never {@code BROWSER}, even once the+ * policy that fed it is gone, and only a smart folder's is reachable from here.+ */+ public static DocumentLocation of(FileRunEvent event, ProducingSurface source) {+ if (event.fileId() == null || event.fileId().isBlank()) {+ return UNREACHABLE;+ }+ if (event.sourceId() == null || event.sourceId().isBlank()) {+ return BROWSER;+ }+ return source == ProducingSurface.SMART_FOLDER ? SMART_FOLDER : UNREACHABLE;+ }+ }+public static FileRunEventView of(- FileRunEvent event, List<FileRunEventService.AvailableAction> actions) {+ FileRunEvent event,+ ProducingSurface source,+ List<FileRunEventService.AvailableAction> actions) {FailureKind kind = event.kind();+ DocumentLocation location = DocumentLocation.of(event, source);return new FileRunEventView(event.id(),kind.getId(),@@ -50,7 +84,10 @@ public record FileRunEventView(event.policyId(),event.runId(),event.sourceId(),- event.fileId(),+ // Withheld for anything the client cannot resolve, so a disk path never leaves the+ // server even to a reader entitled to the row.+ location == DocumentLocation.BROWSER ? event.fileId() : null,+ location,event.actor(),event.occurrences(),event.status(),@@ -78,7 +115,7 @@ public record FileRunEventView(action.id().name(),action.labelKey(),action.id().getDefaultLabel(),- action.id().getExecution(),+ action.execution(),action.slot(),action.enabled(),action.disabledReasonKey());diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/ProducingSurface.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/ProducingSurface.javanew file mode 100644index 0000000000..9e055e00ef--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/ProducingSurface.java@@ -0,0 +1,24 @@+package stirling.software.proprietary.failure;++import stirling.software.proprietary.policy.model.Policy;++/**+ * Which surface of the app produced a failure row, read from the producing policy. Not a source: a+ * source is the folder, bucket or webhook a policy pulls from, and a smart folder is a policy.+ */+public enum ProducingSurface {++ /** A processing-folder policy: a folder the server watches for its owner. */+ SMART_FOLDER,++ /** A team policy, run over whatever sources it is bound to. */+ POLICY,++ /** The reader's own editor, with no policy behind the run. */+ EDITOR;++ /** The kind a row's producing policy implies. */+ public static ProducingSurface of(Policy policy) {+ return Policy.SURFACE_PROCESSING_FOLDER.equals(policy.surface()) ? SMART_FOLDER : POLICY;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/RecordFailure.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/RecordFailure.javaindex 8448f26fc3..27dec5b7cd 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/RecordFailure.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/RecordFailure.java@@ -40,8 +40,8 @@ public record RecordFailure(/*** A processor-side run failure. {@code sourceId} says which folder, bucket or webhook fed the- * run, and is the only attribution an unattended failure has: there is no user to name. {@code- * fileId} is the source's opaque reference to the document, already hashed upstream.+ * run; {@code fileId} is the source's reference to the document, which for a folder source is+ * its canonical path and so is never put in a response.*/public static RecordFailure forRun(FailureKind kind,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/RetryInFolderAction.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/RetryInFolderAction.javanew file mode 100644index 0000000000..0556c830ee--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/RetryInFolderAction.java@@ -0,0 +1,98 @@+package stirling.software.proprietary.failure;++import java.util.List;+import java.util.Map;++import org.springframework.stereotype.Component;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.engine.PolicyRunner;+import stirling.software.proprietary.policy.engine.SweepOutcome;+import stirling.software.proprietary.policy.ledger.ClaimState;+import stirling.software.proprietary.policy.ledger.ProcessedLedger;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.store.PolicyStore;++/**+ * Server's half of {@link FailureActionId#OPEN_IN_TOOL}: reruns a smart folder's document. {@link+ * PolicyAccessGuard#canAccess} on the caller, not the row's actor, is the whole check.+ */+@Slf4j+@Component+@RequiredArgsConstructor+public class RetryInFolderAction implements FailureAction {++ private final PolicyStore policyStore;+ private final PolicyAccessGuard policyAccessGuard;+ private final ProcessedLedger processedLedger;+ private final PolicyRunner policyRunner;+ private final FileRunEventStore store;++ @Override+ public FailureActionId id() {+ return FailureActionId.OPEN_IN_TOOL;+ }++ @Override+ public FileRunEvent execute(FileRunEvent event, Map<String, String> inputs, String actor) {+ Policy policy = ownedFolderFor(event);+ String identity = event.fileId();+ if (identity == null || identity.isBlank()) {+ throw new FailureActionException(+ FailureActionException.Reason.ACTION_NOT_DECLARED,+ "This failure names no document to run again");+ }++ // Taken from the row, never from the caller: the one file this incident is about is the+ // only one a press can reach, so no input can widen it to a sibling or to another folder.+ ClaimState parked = processedLedger.statesFor(policy.id(), List.of(identity)).get(identity);+ if (!processedLedger.forgetFailure(policy.id(), identity)) {+ throw new FailureActionException(+ FailureActionException.Reason.NOTHING_TO_RUN,+ "This document has no parked failure to run again");+ }+ SweepOutcome outcome = policyRunner.runFile(policy, identity);+ // A paused or unreadable folder, a missing licence, or a file that has since left the+ // folder all yield no run. The row stays open, and the failure is parked again at the+ // gate it had, so the next press finds something to run rather than "no parked failure".+ if (outcome.runIds().isEmpty()) {+ if (parked != null) {+ processedLedger.settle(+ policy.id(), identity, parked.gate(), parked.contentHash(), false);+ }+ throw new FailureActionException(+ FailureActionException.Reason.NOTHING_TO_RUN,+ "This document could not be run again: the folder is paused, unreadable, or"+ + " no longer holds it");+ }++ // Closed on dispatch, not on the re-run's outcome: the run is asynchronous, and a repeat+ // failure records its own incident, which folds back onto this row by dedup key.+ return store.applyStatus(event.id(), event.teamId(), FileRunEventStatus.RESOLVED, actor);+ }++ /**+ * The folder this row came from, if the caller owns it. Every refusal is the same {@code+ * EVENT_NOT_FOUND}, so a caller cannot tell a folder that is not theirs from one that is gone.+ */+ private Policy ownedFolderFor(FileRunEvent event) {+ if (event.policyId() == null || event.policyId().isBlank()) {+ throw notTheirs(event);+ }+ return policyStore+ .get(event.policyId())+ .filter(policy -> Policy.SURFACE_PROCESSING_FOLDER.equals(policy.surface()))+ .filter(policyAccessGuard::canAccess)+ .orElseThrow(() -> notTheirs(event));+ }++ private FailureActionException notTheirs(FileRunEvent event) {+ log.debug("Refused a folder retry on event {} (policy {})", event.id(), event.policyId());+ return new FailureActionException(+ FailureActionException.Reason.EVENT_NOT_FOUND,+ "No smart folder to run this document in");+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationController.java b/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationController.javaindex 4c51dd4e72..249fc6756d 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationController.java@@ -20,8 +20,8 @@ import lombok.RequiredArgsConstructor;import stirling.software.proprietary.failure.FailureActionException;/**- * Open to any authenticated user: each source scopes its own rows. Every action runs on the- * client's own device, so the only write is it reporting a fix.+ * Open to any authenticated user: each source scopes its own rows. An action runs wherever the+ * document is, so the writes here are a client reporting a fix and a server-run action.*/@RestController@RequestMapping("/api/v1/notifications")@@ -70,6 +70,25 @@ public class NotificationController {}}+ @PostMapping("/{notificationId}/actions/{actionId}")+ @Operation(+ summary = "Run one of a notification's server-side actions",+ description =+ "Takes the prefixed notification id, not the producing row's id. Only actions"+ + " the row already offers this caller can be run; the producing"+ + " service re-checks that, and the action authorises its own effects.")+ public NotificationView act(+ @PathVariable String notificationId, @PathVariable String actionId) {+ try {+ return notifications.act(notificationId, actionId);+ } catch (IllegalArgumentException e) {+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e);+ } catch (FailureActionException e) {+ throw new ResponseStatusException(+ FailureActionException.statusOf(e.getReason()), e.getMessage(), e);+ }+ }+/** Wrapped so paging or a total can be added without breaking clients. */public record NotificationsResponse(List<NotificationView> notifications,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationService.java b/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationService.javaindex 3b30e9be0f..6be6b5ab2f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationService.java@@ -1,14 +1,25 @@package stirling.software.proprietary.notification;+import java.util.HashMap;import java.util.List;+import java.util.Map;+import java.util.Objects;+import java.util.stream.Collectors;import org.springframework.stereotype.Service;import lombok.RequiredArgsConstructor;+import stirling.software.proprietary.failure.FailureActionId;+import stirling.software.proprietary.failure.FailureScope;import stirling.software.proprietary.failure.FileRunEvent;import stirling.software.proprietary.failure.FileRunEventService;import stirling.software.proprietary.failure.FileRunEventView;+import stirling.software.proprietary.failure.Ownership;+import stirling.software.proprietary.failure.ProducingSurface;+import stirling.software.proprietary.policy.ledger.StorageFileIdentities;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.repository.StoredFileRepository;/*** Derived on read rather than stored: one source today, and a table would need a write path,@@ -19,10 +30,11 @@ import stirling.software.proprietary.failure.FileRunEventView;public class NotificationService {private final FileRunEventService fileRunEvents;+ private final StoredFileRepository storedFiles;/**- * Newest first, and only open failures about a document: one already dealt with is not news,- * and a row naming no file has nothing the bell can offer beyond saying so.+ * Newest first, and only open failures that name a document or a source that could not be read:+ * one already dealt with is not news, and a row naming neither has nothing to offer.** <p>Filtered on the named file rather than the kind's scope, because a RUN-scoped kind still* names one when the editor reported it: a failed tool run belongs here. Applied after the@@ -30,10 +42,60 @@ public class NotificationService {* where those are meant to be read, and it lists them unfiltered.*/public List<NotificationView> list(int limit) {- return fileRunEvents.list(null, false, null, limit).stream()- .filter(event -> event.fileId() != null && !event.fileId().isBlank())- .map(this::fromFailure)- .toList();+ // One lookup per distinct policy rather than per row: a folder that fails a whole batch is+ // one policy and twenty rows.+ Map<String, ProducingSurface> kinds = new HashMap<>();+ List<FileRunEvent> events =+ fileRunEvents.list(null, false, null, limit).stream()+ .filter(+ event ->+ namesADocument(event)+ || event.scope() == FailureScope.SOURCE)+ .toList();+ Map<Long, StoredFile> named = storedFilesNamedBy(events);+ return events.stream().map(event -> fromFailure(event, kinds, named)).toList();+ }++ /**+ * The stored files behind the reader's own rows, in one query for the page. Only a+ * storage-backed folder's identity resolves; a disk folder's is a path and stays unnamed.+ */+ private Map<Long, StoredFile> storedFilesNamedBy(List<FileRunEvent> events) {+ List<Long> ids =+ events.stream()+ .filter(event -> fileRunEvents.ownershipOf(event) == Ownership.MINE)+ .map(event -> StorageFileIdentities.storedFileIdOf(event.fileId()))+ .filter(Objects::nonNull)+ .distinct()+ .toList();+ if (ids.isEmpty()) {+ return Map.of();+ }+ return storedFiles.findAllById(ids).stream()+ .collect(Collectors.toMap(StoredFile::getId, file -> file));+ }++ /** What to call the document, for the row's own owner and nobody else. */+ private static String documentNameFor(+ FileRunEvent event, Ownership ownership, Map<Long, StoredFile> named) {+ if (ownership != Ownership.MINE || event.actor() == null) {+ return null;+ }+ Long storedFileId = StorageFileIdentities.storedFileIdOf(event.fileId());+ // Guarded rather than looked up: an immutable empty map refuses a null key.+ StoredFile file = storedFileId == null ? null : named.get(storedFileId);+ // Belt and braces over the ownership above: that says the reader raised the row, this says+ // the document is theirs. A row can outlive the file it named.+ if (file == null+ || file.getOwner() == null+ || !event.actor().equals(file.getOwner().getUsername())) {+ return null;+ }+ return file.getOriginalFilename();+ }++ private static boolean namesADocument(FileRunEvent event) {+ return event.fileId() != null && !event.fileId().isBlank();}/** Whether the caller sees the whole team's incidents rather than only their own. */@@ -53,6 +115,18 @@ public class NotificationService {};}+ /**+ * Run one of the row's own server actions, addressed by prefixed id. Nothing is authorised+ * here: the producing service re-checks the row and the action.+ */+ public NotificationView act(String notificationId, String actionId) {+ NotificationSource.QualifiedId qualified = qualify(notificationId);+ return switch (qualified.source()) {+ case FAILURE ->+ fromFailure(fileRunEvents.dispatch(qualified.rowId(), actionId, Map.of()));+ };+ }+/** The source and row id behind a notification id, refusing anything that is not one. */private static NotificationSource.QualifiedId qualify(String notificationId) {return NotificationSource.parse(notificationId)@@ -62,29 +136,62 @@ public class NotificationService {"Not a notification id: " + notificationId));}- /** Prefixes the row id on the way out, so it is never sent bare. */+ /** One row on its own, looked up for itself. */private NotificationView fromFailure(FileRunEvent event) {+ return fromFailure(event, new HashMap<>(), storedFilesNamedBy(List.of(event)));+ }++ /** Prefixes the row id on the way out, so it is never sent bare. */+ private NotificationView fromFailure(+ FileRunEvent event, Map<String, ProducingSurface> kinds, Map<Long, StoredFile> named) {+ ProducingSurface source = fileRunEvents.producingSurfaceOf(event, kinds);+ FileRunEventView.DocumentLocation location =+ FileRunEventView.DocumentLocation.of(event, source);+ boolean resolvableHere = location == FileRunEventView.DocumentLocation.BROWSER;+ // A smart folder's document, or the folder itself when it could not be read: the server+ // keeps these for the reader, and a member's bell shows them without a local file.+ boolean heldByServer =+ location == FileRunEventView.DocumentLocation.SMART_FOLDER+ || (event.scope() == FailureScope.SOURCE+ && source == ProducingSurface.SMART_FOLDER);+ Ownership ownership = fileRunEvents.ownershipOf(event);return new NotificationView(NotificationSource.FAILURE.qualify(event.id()),NotificationSource.FAILURE,event.kind().getId(),event.origin(),- fileRunEvents.ownershipOf(event),+ ownership,event.severity(),event.status(),event.kind().getTitleKey(),event.kind().getDefaultTitle(),event.detail(),- event.fileId(),+ // Only an id this reader's own client minted. A source's reference is a location on+ // the server's disk, and no client has anything to match it against.+ resolvableHere ? event.fileId() : null,+ resolvableHere ? null : documentNameFor(event, ownership, named),+ location,+ heldByServer,event.sourceId(),event.policyId(),event.occurrences(),event.createdAt(),event.lastSeenAt(),- // A disposition such as Dismiss belongs to the review surface, not the bell.- fileRunEvents.availableActions(event).stream()- .filter(action -> !action.id().runsOnServer())- .map(FileRunEventView.ActionView::of)- .toList());+ bellActions(event, source));+ }++ /**+ * What the bell may offer: every fix, including the ones the server carries out, but not a+ * disposition, which is the review surface's to apply. A new disposition belongs in this list.+ */+ private List<FileRunEventView.ActionView> bellActions(+ FileRunEvent event, ProducingSurface source) {+ return fileRunEvents.availableActions(event, source).stream()+ .filter(+ action ->+ action.id() != FailureActionId.DISMISS+ && action.id() != FailureActionId.ACKNOWLEDGE)+ .map(FileRunEventView.ActionView::of)+ .toList();}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationView.java b/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationView.javaindex be04153686..9f9aef7077 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationView.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/notification/NotificationView.java@@ -10,8 +10,8 @@ import stirling.software.proprietary.failure.FileRunEventView;import stirling.software.proprietary.failure.Ownership;/**- * A source's row flattened to what a bell renders. {@code fileId} is an opaque reference, never a- * name, and two id spaces share it: {@code sourceId} tells them apart.+ * A source's row flattened to what a bell renders. {@code fileId} is present only when {@code+ * documentLocation} is {@code BROWSER}; a document the server holds is named only for its owner.*/public record NotificationView(String id,@@ -25,6 +25,17 @@ public record NotificationView(String defaultTitle,String detail,String fileId,+ /**+ * What to call a document the reader cannot hold, for the person the row belongs to and+ * nobody else. Null unless a storage-backed folder can answer; never a path.+ */+ String documentName,+ FileRunEventView.DocumentLocation documentLocation,+ /**+ * Whether the server keeps this row on the reader's behalf: a smart folder's document, or+ * the folder itself when it could not be read. The one rule a member's bell filters on.+ */+ boolean heldByServer,String sourceId,String policyId,int occurrences,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 59ba7f79d5..02e5773cf7 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@@ -323,7 +323,14 @@ public class PolicyEngine {taskManager.putMetadata(runId, "policyId", policyId);}PolicyRun run =- new PolicyRun(runId, policyId, definition, sourceId, fileIdentity, triggeringUser);+ new PolicyRun(+ runId,+ policyId,+ definition,+ sourceId,+ fileIdentity,+ triggeringUser,+ fileOwner);taskManager.putMetadata(runId, "externalOutput", String.valueOf(run.externalOutput()));registry.register(run);return run;@@ -484,7 +491,7 @@ public class PolicyEngine {run.getRunId(),run.getPolicyId(),run.getSourceId(),- run.getTriggeringUser(),+ run.failureActor(),message);completion.complete(run);}@@ -504,10 +511,8 @@ public class PolicyEngine {* Record why a run failed. Called after the run's own state transition and task-manager update,* so a recording problem cannot change the outcome the caller observes.*- * <p>The actor is the run's triggering user, not the MDC audit principal: that carries the- * BILLING identity, which for a stored policy is always its owner. Reading it here filed every- * failure under the owner — hiding an attended failure from the member who caused it and holds- * the document, and leaving an unattended sweep's failure looking attended.+ * <p>The actor is the run's own, not the MDC audit principal, which carries the billing+ * identity: for a stored policy always its owner. Unattended, it falls back to the document's.*/private void recordFailure(PolicyRun run, String message, Throwable cause) {failureRecorder.recordRunFailure(@@ -515,7 +520,7 @@ public class PolicyEngine {run.getPolicyId(),run.getSourceId(),run.getFileIdentity(),- run.getTriggeringUser(),+ run.failureActor(),message,cause);}diff --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 7054285496..2f2d44597a 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,6 +1,7 @@package stirling.software.proprietary.policy.engine;import java.io.IOException;+import java.nio.file.FileSystemException;import java.time.Duration;import java.util.ArrayList;import java.util.List;@@ -15,6 +16,10 @@ import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.failure.FailureKind;+import stirling.software.proprietary.failure.PolicyFailureRecorder;+import stirling.software.proprietary.policy.config.FolderAccessDeniedException;+import stirling.software.proprietary.policy.config.FolderAccessGuard;import stirling.software.proprietary.policy.config.PolicyAccessGuard;import stirling.software.proprietary.policy.input.InputSource;import stirling.software.proprietary.policy.input.ResolvedInput;@@ -52,6 +57,7 @@ public class PolicyRunner {private final ApplicationProperties applicationProperties;private final PolicyAccessGuard policyAccessGuard;private final DatabaseLicenseGuard databaseLicenseGuard;+ private final PolicyFailureRecorder failureRecorder;private final ApplicationEventPublisher eventPublisher;/**@@ -218,6 +224,16 @@ public class PolicyRunner {return policyEngine.cancelAllFor(policyId);}+ private static String unreadableFolderReason(Exception e) {+ if (e instanceof FolderAccessDeniedException) {+ return "The folder is outside the roots this server permits";+ }+ if (e instanceof FileSystemException fs && fs.getReason() != null) {+ return fs.getReason();+ }+ return "The folder could not be listed";+ }+/*** 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@@ -268,6 +284,27 @@ public class PolicyRunner {spec.type(),policy.id(),e.getMessage());+ // Recorded, not just logged, for a disk folder that could not be listed or that the+ // server's allowlist now refuses: its owner would otherwise never hear that the folder+ // stopped working, and only they can fix it. A bucket's SDK error or a bug in a source+ // is neither, so it stays a log line. The reason without the path: reviewers across+ // the team read this, and the guard's own message names the folder.+ boolean folderUnreadable =+ FolderAccessGuard.FOLDER_TYPE.equals(spec.type())+ && (e instanceof IOException+ || e instanceof FolderAccessDeniedException);+ if (folderUnreadable) {+ // The source's owner, as a document failure is filed under: a team policy can be+ // bound to a folder somebody else set up, and that person is the one who can fix+ // it.+ failureRecorder.recordRunFailureAs(+ FailureKind.SOURCE_UNREADABLE,+ null,+ policy.id(),+ storedSource.id(),+ storedSource.owner(),+ unreadableFolderReason(e));+ }context.vetoCleanup();return List.of();}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.javaindex d9e229a0b9..b5bf315a0e 100644--- 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.java@@ -22,8 +22,25 @@ public final class StorageFileIdentities {private StorageFileIdentities() {}+ private static final String PREFIX = "storage:";+public static String identity(StoredFile file) {- return "storage:" + file.getId();+ return PREFIX + file.getId();+ }++ /**+ * The row id behind an identity this class wrote, or null for anything else, including a folder+ * source's path identity. Lives beside {@link #identity} so the two cannot drift.+ */+ public static Long storedFileIdOf(String identity) {+ if (identity == null || !identity.startsWith(PREFIX)) {+ return null;+ }+ try {+ return Long.valueOf(identity.substring(PREFIX.length()));+ } catch (NumberFormatException e) {+ return null;+ }}public static String gate(StoredFile file) {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 3bdee317e5..574b5f1f18 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@@ -30,11 +30,17 @@ public class PolicyRun {private final PipelineDefinition definition;/**- * The source's opaque reference to the document this run is about; null for an ad-hoc run or a- * source that names no document. Hashed upstream, so never a path or a filename.+ * The source's reference to the document this run is about, or null when there is none. A+ * folder source builds it from the canonical path, so it must never reach a response.*/private final String fileIdentity;+ /**+ * Whose document this run is about: the source's owner for a source-fed run, the triggering+ * user otherwise. A failure is filed under this person when nobody attended the run.+ */+ private final String fileOwner;+/*** The user who triggered this run, or null when nothing attended it (a trigger-fired sweep).* Recorded as a failure's actor, so an attended failure is handed to the person holding the@@ -85,13 +91,23 @@ public class PolicyRun {PipelineDefinition definition,String sourceId,String fileIdentity,- String triggeringUser) {+ String triggeringUser,+ String fileOwner) {this.runId = runId;this.policyId = policyId;this.sourceId = sourceId;this.definition = definition;this.fileIdentity = fileIdentity;this.triggeringUser = triggeringUser;+ this.fileOwner = fileOwner;+ }++ /**+ * Who a failure on this run belongs to: whoever attended it, or the document's owner when+ * nobody did. Null only when neither is known, which is an install with no accounts.+ */+ public String failureActor() {+ return triggeringUser != null ? triggeringUser : fileOwner;}/** True when results are sent elsewhere and must not replace the editor's input. */diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.javaindex 2c48f1724c..c7f395c2aa 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java@@ -240,10 +240,11 @@ class FailureKindTest {@Testvoid offersARetryToItsOwnerAndTheRunToWhoeverReviews() {- // No known fix, so no resolution; a retry is still worth offering for a one-off.+ // No known fix, so the retry is the resolution: these are often one-offs. One offer+ // wherever the document is; FileRunEventService says per row which side runs it.assertThat(FailureKind.UNKNOWN.getOfferedActions()).containsExactly(- offered(FailureActionId.OPEN_IN_TOOL, OWNER, SECONDARY, "openInTool"),+ offered(FailureActionId.OPEN_IN_TOOL, OWNER, RESOLUTION, "openInTool"),offered(FailureActionId.VIEW_FILE, OWNER, SECONDARY, "viewFile"),offered(FailureActionId.VIEW_IN_PROCESSOR,@@ -459,12 +460,24 @@ class FailureKindTest {FailureKind.INPUT_EMPTY,FailureKind.INPUT_UNAVAILABLE,FailureKind.TOOL_NOT_INSTALLED,+ FailureKind.SOURCE_UNREADABLE,FailureKind.STEP_CANNOT_RENDER_PAGE,FailureKind.STEP_TOOL_FAILED,FailureKind.STEP_INTERRUPTED,FailureKind.STEP_PAGE_TOO_LARGE,- FailureKind.STEP_MISCONFIGURED,- FailureKind.UNKNOWN);+ FailureKind.STEP_MISCONFIGURED);+ }++ @Test+ void unknownsOnlyResolutionIsThePlainRetry() {+ // The exception to the rule above: an unrecognised failure may well be a one-off.+ // Other retry-first kinds offer it as an action, a guess rather than the fix.+ assertThat(+ FailureKind.UNKNOWN.getOfferedActions().stream()+ .filter(offer -> offer.slot() == RESOLUTION)+ .map(FailureKind.OfferedAction::id)+ .toList())+ .containsExactly(FailureActionId.OPEN_IN_TOOL);}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventControllerTest.javaindex 6cf56a1ec7..dcede5ae28 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventControllerTest.java@@ -25,6 +25,7 @@ import org.springframework.web.server.ResponseStatusException;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.UserServiceInterface;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.store.PolicyStore;/*** Tests for {@link FileRunEventController}: the wire shape, the status mapping for each refusal@@ -37,6 +38,7 @@ class FileRunEventControllerTest {@Mock private PolicyManagementAuthority authority;@Mock private UserServiceInterface userService;+ @Mock private PolicyStore policyStore;private FileRunEventStore store;private FileRunEventController controller;@@ -51,7 +53,8 @@ class FileRunEventControllerTest {List.of(new AcknowledgeAction(store), new DismissAction(store)));controller =new FileRunEventController(- new FileRunEventService(store, registry, authority, userService, props));+ new FileRunEventService(+ store, registry, authority, userService, props, policyStore));lenient().when(authority.canEditPolicies()).thenReturn(true);lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);@@ -435,7 +438,8 @@ class FileRunEventControllerTest {new DismissAction(store))),authority,userService,- unsecured));+ unsecured,+ policyStore));assertThatCode(() -> noLogin.list(null, false, null, null)).doesNotThrowAnyException();// Not merely permitted: the role is never consulted at all, which is what makes the@@ -480,7 +484,8 @@ class FileRunEventControllerTest {new DismissAction(store))),authority,userService,- unsecured));+ unsecured,+ policyStore));given(FailureKind.UNKNOWN, null, "unteamed");given(FailureKind.UNKNOWN, TEAM, "teamed");diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventHttpIntegrationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventHttpIntegrationTest.javaindex 4bf886dbc8..3928831313 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventHttpIntegrationTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventHttpIntegrationTest.java@@ -26,6 +26,9 @@ import org.springframework.context.annotation.Bean;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.UserServiceInterface;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.store.PolicyStore;import tools.jackson.databind.JsonNode;import tools.jackson.databind.json.JsonMapper;@@ -75,6 +78,23 @@ class FileRunEventHttpIntegrationTest {.id();}+ /** As {@link #seed}, for a row a source fed rather than a client. */+ private String seedFromSource(FailureKind kind, String sourceId, String identity) {+ FileRunEventStore store = new FileRunEventStore(repository);+ return store.record(+ new RecordFailure(+ kind,+ FailureOrigin.POLICY,+ TEAM,+ "[email protected]",+ "policy-1",+ "run-1",+ sourceId,+ identity,+ "boom"))+ .id();+ }+private HttpResponse<String> get(String path) throws Exception {return http.send(HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)).GET().build(),@@ -96,6 +116,23 @@ class FileRunEventHttpIntegrationTest {@DisplayName("the read path")class ReadPath {+ @Test+ void serialisesASourceFedRowWithoutThePathBehindIt() throws Exception {+ // The portal is the second surface that renders these rows, and it maps them itself,+ // so the withholding is asserted here too rather than only on the bell's projection.+ seedFromSource(+ FailureKind.UNKNOWN,+ "src-downloads",+ "/Users/someone/Documents/Payroll/march.pdf");++ HttpResponse<String> response = get("/api/v1/file-run-events");++ JsonNode row = mapper.readTree(response.body()).get("events").get(0);+ assertThat(row.get("documentLocation").asString()).isEqualTo("SMART_FOLDER");+ assertThat(row.get("fileId").isNull()).isTrue();+ assertThat(response.body()).doesNotContain("/Users/someone", "march.pdf");+ }+@Testvoid serialisesAnEventWithItsFacetsCopyKeysAndResolvedActions() throws Exception {seed(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "acme-msa", "locked tight");@@ -420,6 +457,34 @@ class FileRunEventHttpIntegrationTest {return new DismissAction(store);}+ /**+ * A stand-in, so the registry's completeness check passes without dragging a ledger and a+ * runner into an HTTP-layer test. Covered by {@code RetryInFolderActionTest}.+ */+ @Bean+ FailureAction retryInFolderAction() {+ return new NoopFolderAction(FailureActionId.OPEN_IN_TOOL);+ }++ /** Every source-fed row in these tests came from a smart folder. */+ @Bean+ PolicyStore policyStore() {+ PolicyStore store = org.mockito.Mockito.mock(PolicyStore.class);+ Policy folder =+ new Policy(+ "p-1",+ "Payroll",+ ACTOR,+ true,+ List.of(),+ List.of(),+ OutputSpec.inline())+ .withSurface(Policy.SURFACE_PROCESSING_FOLDER);+ org.mockito.Mockito.when(store.get(org.mockito.ArgumentMatchers.anyString()))+ .thenReturn(java.util.Optional.of(folder));+ return store;+ }+@BeanApplicationProperties applicationProperties() {ApplicationProperties props = new ApplicationProperties();@@ -450,8 +515,9 @@ class FileRunEventHttpIntegrationTest {FailureActionRegistry registry,PolicyManagementAuthority authority,UserServiceInterface users,- ApplicationProperties props) {- return new FileRunEventService(store, registry, authority, users, props);+ ApplicationProperties props,+ PolicyStore policyStore) {+ return new FileRunEventService(store, registry, authority, users, props, policyStore);}@Beandiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventServiceTest.javaindex a811875aab..a7e0a65217 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FileRunEventServiceTest.java@@ -3,6 +3,7 @@ package stirling.software.proprietary.failure;import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatCode;import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.when;@@ -11,6 +12,7 @@ import java.time.Instant;import java.util.Arrays;import java.util.List;import java.util.Map;+import java.util.Optional;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;@@ -23,6 +25,9 @@ import org.mockito.junit.jupiter.MockitoExtension;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.UserServiceInterface;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.store.PolicyStore;/*** Tests for {@link FileRunEventService}: team scoping, the declaration guard, transition legality,@@ -36,6 +41,7 @@ class FileRunEventServiceTest {@Mock private PolicyManagementAuthority authority;@Mock private UserServiceInterface userService;+ @Mock private PolicyStore policyStore;private FileRunEventStore store;private FileRunEventService service;@@ -48,10 +54,15 @@ class FileRunEventServiceTest {store = new FileRunEventStore(new InMemoryFileRunEventRepository());FailureActionRegistry registry =new FailureActionRegistry(- List.of(new AcknowledgeAction(store), new DismissAction(store)));+ List.of(+ new AcknowledgeAction(store),+ new DismissAction(store),+ new NoopFolderAction(FailureActionId.OPEN_IN_TOOL)));registry.verifyEveryDeclaredActionHasAHandler();- service = new FileRunEventService(store, registry, authority, userService, props);+ service =+ new FileRunEventService(+ store, registry, authority, userService, props, policyStore);lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);lenient().when(userService.getCurrentUsername()).thenReturn(ACTOR);@@ -65,6 +76,34 @@ class FileRunEventServiceTest {}/** As {@link #given} but naming who the incident belongs to, which decides its ownership. */+ /**+ * A row from a smart folder the given person owns, which is where a server fix is reachable.+ */+ private FileRunEvent givenInAFolderOwnedBy(String owner) {+ when(policyStore.get(anyString()))+ .thenReturn(+ Optional.of(+ new Policy(+ "policy-1",+ "Payroll",+ owner,+ true,+ List.of(),+ List.of(),+ OutputSpec.inline())+ .withSurface(Policy.SURFACE_PROCESSING_FOLDER)));+ return store.record(+ RecordFailure.forRun(+ FailureKind.UNKNOWN,+ TEAM,+ owner,+ "policy-1",+ "run-1",+ "src-downloads",+ "/folder/march.pdf",+ "boom"));+ }+private FileRunEvent givenHitBy(String actor, FailureKind kind, Long teamId, String fileId) {return store.record(new RecordFailure(@@ -367,7 +406,7 @@ class FileRunEventServiceTest {for (FailureKind kind : FailureKind.values()) {FileRunEvent event = given(kind, TEAM, "f-" + kind.getId());for (FailureActionId action : kind.getActions()) {- if (action.runsOnServer()) {+ if (action.executionFor(false) == FailureActionId.Execution.SERVER) {continue;}assertThatThrownBy(() -> service.dispatch(event.id(), action.name(), Map.of()))@@ -400,7 +439,8 @@ class FileRunEventServiceTest {new FailureActionRegistry(List.of(new AcknowledgeAction(store))),authority,userService,- props);+ props,+ policyStore);assertThatThrownBy(() -> missingHandler.dispatch(event.id(), "DISMISS", Map.of())).isInstanceOf(FailureActionException.class)@@ -423,6 +463,52 @@ class FileRunEventServiceTest {}}+ @Nested+ @DisplayName("an owner's fix is refused to whoever merely reviews it")+ class DispatchAudience {++ @Test+ void aReviewerCannotRunAnOwnersFixOnTheirColleaguesDocument() {+ // The whole point of the check: a leader reads the team's rows, so without it the only+ // thing between them and a colleague's document is the handler's own guard.+ FileRunEvent theirs = givenInAFolderOwnedBy("[email protected]");++ assertThatThrownBy(() -> service.dispatch(theirs.id(), "OPEN_IN_TOOL", Map.of()))+ .isInstanceOf(FailureActionException.class)+ .extracting(e -> ((FailureActionException) e).getReason())+ .isEqualTo(FailureActionException.Reason.ACTION_NOT_THEIRS);+ }++ @Test+ void refusedBeforeTheHandlerIsAskedToDoAnything() {+ // The registry's stand-in throws if reached, so this asserts the refusal is the+ // service's rather than something the handler happened to catch.+ FileRunEvent theirs = givenInAFolderOwnedBy("[email protected]");++ assertThatThrownBy(() -> service.dispatch(theirs.id(), "OPEN_IN_TOOL", Map.of()))+ .isNotInstanceOf(UnsupportedOperationException.class);+ }++ @Test+ void theOwnerOfTheFolderStillRunsIt() {+ FileRunEvent mine = givenInAFolderOwnedBy(ACTOR);++ // Reaches the registry's stand-in, which is as far as this test can follow it.+ assertThatThrownBy(() -> service.dispatch(mine.id(), "OPEN_IN_TOOL", Map.of()))+ .isInstanceOf(UnsupportedOperationException.class);+ }++ @Test+ void aReviewerCanStillDismissAColleaguesRow() {+ // Dispositions are for anyone who sees the row; only an owner's fix is narrowed.+ FileRunEvent theirs =+ givenHitBy("[email protected]", FailureKind.UNKNOWN, TEAM, "f1");++ assertThat(service.dispatch(theirs.id(), "DISMISS", Map.of()).status())+ .isEqualTo(FileRunEventStatus.DISMISSED);+ }+ }+@Nested@DisplayName("ownership is derived against whoever is reading")class OwnershipDerivation {@@ -570,6 +656,32 @@ class FileRunEventServiceTest {});}+ @Test+ void aRowAboutTheSourceItselfKeepsItsOwnerActionUsableThoughItNamesNoDocument() {+ // The folder is the subject, and the one thing offered its owner opens the processor,+ // which needs no document. Greying it out would answer a question nobody asked.+ FileRunEvent folder =+ store.record(+ RecordFailure.forRun(+ FailureKind.SOURCE_UNREADABLE,+ TEAM,+ ACTOR,+ "policy-1",+ "run-1",+ "src-downloads",+ null,+ "Permission denied"));++ assertThat(service.availableActions(folder))+ .filteredOn(action -> action.id() == FailureActionId.VIEW_IN_PROCESSOR)+ .singleElement()+ .satisfies(+ action -> {+ assertThat(action.enabled()).isTrue();+ assertThat(action.disabledReasonKey()).isNull();+ });+ }+@Testvoid aRowThatNamesADocumentKeepsItsOwnerActionsUsable() {FileRunEvent withDocument =@@ -602,7 +714,8 @@ class FileRunEventServiceTest {new FailureActionRegistry(List.of(new DismissAction(store))),authority,userService,- props);+ props,+ policyStore);FileRunEvent event = givenHitBy(null, FailureKind.INPUT_PASSWORD_PROTECTED, null, "f1");assertThat(unsecured.availableActions(event))@@ -759,7 +872,8 @@ class FileRunEventServiceTest {new FailureActionRegistry(List.of(new AcknowledgeAction(store), new DismissAction(store)));FileRunEventService unsecured =- new FileRunEventService(store, registry, authority, userService, props);+ new FileRunEventService(+ store, registry, authority, userService, props, policyStore);given(FailureKind.UNKNOWN, null, "unteamed");given(FailureKind.UNKNOWN, TEAM, "teamed");@@ -801,13 +915,17 @@ class FileRunEventServiceTest {void acceptsACompleteSetOfHandlers() {FailureActionRegistry complete =new FailureActionRegistry(- List.of(new AcknowledgeAction(store), new DismissAction(store)));+ List.of(+ new AcknowledgeAction(store),+ new DismissAction(store),+ new NoopFolderAction(FailureActionId.OPEN_IN_TOOL)));complete.verifyEveryDeclaredActionHasAHandler();for (FailureActionId id : FailureActionId.values()) {- // Only server actions need a handler, which is why the boot check ignores the rest.- assertThat(complete.find(id).isPresent()).isEqualTo(id.runsOnServer());+ // Only what the server can run needs a handler, which is why the boot check+ // ignores the rest.+ assertThat(complete.find(id).isPresent()).isEqualTo(id.canRunOnServer());}}@@ -816,7 +934,10 @@ class FileRunEventServiceTest {// Otherwise every client action would need an empty handler beside it.FailureActionRegistry serverOnly =new FailureActionRegistry(- List.of(new AcknowledgeAction(store), new DismissAction(store)));+ List.of(+ new AcknowledgeAction(store),+ new DismissAction(store),+ new NoopFolderAction(FailureActionId.OPEN_IN_TOOL)));assertThatCode(serverOnly::verifyEveryDeclaredActionHasAHandler).doesNotThrowAnyException();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/NoopFolderAction.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/NoopFolderAction.javanew file mode 100644index 0000000000..64efac7c85--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/NoopFolderAction.java@@ -0,0 +1,25 @@+package stirling.software.proprietary.failure;++import java.util.Map;++/**+ * Satisfies the registry's "every declared action has a handler" check for tests about something+ * else. The real handler needs a policy store, a ledger and a runner, and has its own tests.+ */+final class NoopFolderAction implements FailureAction {+ private final FailureActionId id;++ NoopFolderAction(FailureActionId id) {+ this.id = id;+ }++ @Override+ public FailureActionId id() {+ return id;+ }++ @Override+ public FileRunEvent execute(FileRunEvent event, Map<String, String> inputs, String actor) {+ throw new UnsupportedOperationException("not the subject of this test");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationProjectionTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationProjectionTest.javaindex f5b3fab746..e22412c109 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationProjectionTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationProjectionTest.java@@ -1,10 +1,15 @@package stirling.software.proprietary.failure;import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;import java.util.List;+import java.util.Map;+import java.util.Optional;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;@@ -21,6 +26,12 @@ import stirling.software.proprietary.notification.NotificationService;import stirling.software.proprietary.notification.NotificationSource;import stirling.software.proprietary.notification.NotificationView;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.store.PolicyStore;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.repository.StoredFileRepository;/*** What the bell is given to render: never a raw event id, and only the actions the client itself@@ -37,6 +48,9 @@ class NotificationProjectionTest {private FileRunEventStore store;private FileRunEventService failures;+ @Mock private PolicyStore policyStore;+ @Mock private StoredFileRepository storedFiles;+private NotificationController controller;@BeforeEach@@ -51,12 +65,27 @@ class NotificationProjectionTest {List.of(new AcknowledgeAction(store), new DismissAction(store))),authority,userService,- props);- controller = new NotificationController(new NotificationService(failures));+ props,+ policyStore);+ controller = new NotificationController(new NotificationService(failures, storedFiles));lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);lenient().when(authority.canEditPolicies()).thenReturn(true);lenient().when(userService.getCurrentUsername()).thenReturn(ACTOR);+ // Every source-fed row here came from a smart folder unless a test says otherwise.+ lenient().when(policyStore.get(anyString())).thenReturn(Optional.of(smartFolder()));+ }++ private static Policy smartFolder() {+ return new Policy(+ "policy-1",+ "Payroll",+ ACTOR,+ true,+ List.of(),+ List.of(),+ OutputSpec.inline())+ .withSurface(Policy.SURFACE_PROCESSING_FOLDER);}private FileRunEvent given(FailureKind kind, String actor, String fileId) {@@ -101,7 +130,10 @@ class NotificationProjectionTest {// The queue's own offers minus the server's: a bell offering different ones would lie.assertThat(notification.actions()).containsExactlyElementsOf(- FileRunEventView.of(mine, failures.availableActions(mine))+ FileRunEventView.of(+ mine,+ ProducingSurface.EDITOR,+ failures.availableActions(mine)).actions().stream().filter(@@ -148,9 +180,9 @@ class NotificationProjectionTest {}@Test- void namesTheSourceThatFedAnUnattendedRunSoItsFileIdIsNotMistakenForAClientsOwn() {- // Without the source a client looks up a hash it can never resolve and calls it- // missing.+ void withholdsTheReferenceBehindASourceFedRow() {+ // A folder source builds its identity from the file's canonical path, so sending the+ // reference would hand every reader a location on the operator's disk.store.record(RecordFailure.forRun(FailureKind.INPUT_PASSWORD_PROTECTED,@@ -159,13 +191,190 @@ class NotificationProjectionTest {"policy-1","run-1","source-7",- "hashed-identity",+ "/Users/someone/Documents/Payroll/march.pdf","boom"));NotificationView notification = controller.list(null).notifications().getFirst();assertThat(notification.sourceId()).isEqualTo("source-7");- assertThat(notification.fileId()).isEqualTo("hashed-identity");+ assertThat(notification.documentLocation())+ .isEqualTo(FileRunEventView.DocumentLocation.SMART_FOLDER);+ assertThat(notification.fileId()).isNull();+ }++ @Test+ void aBucketFedPolicyRowIsNotCalledASmartFoldersAndOffersNoFolderRetry() {+ // The same source-fed shape from an S3 or webhook policy. Calling it a smart folder's+ // told the owner so, and offered a retry the folder handler could only refuse.+ lenient()+ .when(policyStore.get(anyString()))+ .thenReturn(Optional.of(smartFolder().withSurface(Policy.SURFACE_POLICY)));+ FileRunEvent row =+ store.record(+ RecordFailure.forRun(+ FailureKind.UNKNOWN,+ TEAM,+ ACTOR,+ "policy-1",+ "run-1",+ "source-s3",+ "s3://bucket/march.pdf",+ "boom"));++ NotificationView notification = controller.list(null).notifications().getFirst();++ assertThat(notification.documentLocation())+ .isEqualTo(FileRunEventView.DocumentLocation.UNREACHABLE);+ // The retry is the browser's here, which holds nothing to run it on, so the bell hides+ // it; and the server will not run it either.+ assertThat(notification.actions())+ .filteredOn(action -> action.id().equals("OPEN_IN_TOOL"))+ .extracting(FileRunEventView.ActionView::execution)+ .containsExactly(FailureActionId.Execution.CLIENT);+ // The reason, not just the type: with no OPEN_IN_TOOL handler registered here, a broken+ // location guard would still throw, as ACTION_NOT_RECOGNISED, and pass a looser check.+ assertThatThrownBy(() -> failures.dispatch(row.id(), "OPEN_IN_TOOL", Map.of()))+ .isInstanceOf(FailureActionException.class)+ .extracting(e -> ((FailureActionException) e).getReason())+ .isEqualTo(FailureActionException.Reason.ACTION_NOT_DISPATCHABLE);+ }++ @Test+ void aSourceFedRowWhosePolicyIsGoneStaysWithheldRatherThanReadingAsTheBrowsers() {+ // The lookup that tells a folder from a bucket can come back empty once the policy is+ // deleted. That must not turn the row into a browser's, or the path behind it leaks.+ lenient().when(policyStore.get(anyString())).thenReturn(Optional.empty());+ FileRunEvent row =+ store.record(+ RecordFailure.forRun(+ FailureKind.INPUT_PASSWORD_PROTECTED,+ TEAM,+ null,+ "policy-gone",+ "run-1",+ "source-7",+ "/Users/someone/Documents/Payroll/march.pdf",+ "boom"));++ NotificationView notification = controller.list(null).notifications().getFirst();++ assertThat(notification.documentLocation())+ .isEqualTo(FileRunEventView.DocumentLocation.UNREACHABLE);+ assertThat(notification.fileId()).isNull();+ // Still a policy's row, never the editor's, so nothing downstream reads it as the+ // browser's own.+ assertThat(failures.producingSurfaceOf(row)).isEqualTo(ProducingSurface.POLICY);+ assertThat(notification.toString()).doesNotContain("Payroll", "march.pdf");+ }++ @Test+ void namesAStoredDocumentForItsOwnerAndNobodyElse() {+ // The one reader entitled to the name already has the file. A storage-backed folder can+ // answer because its identity is the stored row's id.+ User owner = new User();+ owner.setUsername(ACTOR);+ StoredFile file = new StoredFile();+ file.setOwner(owner);+ file.setId(42L);+ file.setOriginalFilename("march.pdf");+ when(storedFiles.findAllById(List.of(42L))).thenReturn(List.of(file));+ store.record(+ RecordFailure.forRun(+ FailureKind.UNKNOWN,+ TEAM,+ ACTOR,+ "policy-1",+ "run-1",+ "source-7",+ "storage:42",+ "boom"));++ assertThat(controller.list(null).notifications().getFirst().documentName())+ .isEqualTo("march.pdf");+ }++ @Test+ void withholdsTheNameFromAReaderWhoIsNotTheRowsOwner() {+ // A leader reads the team's rows. A colleague's filename is not theirs to read, so the+ // lookup never happens.+ store.record(+ RecordFailure.forRun(+ FailureKind.UNKNOWN,+ TEAM,+ "[email protected]",+ "policy-1",+ "run-1",+ "source-7",+ "storage:42",+ "boom"));++ assertThat(controller.list(null).notifications().getFirst().documentName()).isNull();+ verifyNoInteractions(storedFiles);+ }++ @Test+ void withholdsTheNameWhenTheStoredFileBelongsToSomeoneElse() {+ // The row says the reader raised it; the file says otherwise. A row outlives the file+ // it named, and an id can be reused.+ User someoneElse = new User();+ someoneElse.setUsername("[email protected]");+ StoredFile file = new StoredFile();+ file.setOwner(someoneElse);+ file.setId(42L);+ file.setOriginalFilename("payroll.pdf");+ when(storedFiles.findAllById(List.of(42L))).thenReturn(List.of(file));+ store.record(+ RecordFailure.forRun(+ FailureKind.UNKNOWN,+ TEAM,+ ACTOR,+ "policy-1",+ "run-1",+ "source-7",+ "storage:42",+ "boom"));++ assertThat(controller.list(null).notifications().getFirst().documentName()).isNull();+ }++ @Test+ void neverNamesADiskFoldersDocument() {+ // Its identity is a path, so the only name available is the last segment of one - the+ // same disclosure by another route.+ store.record(+ RecordFailure.forRun(+ FailureKind.UNKNOWN,+ TEAM,+ ACTOR,+ "policy-1",+ "run-1",+ "source-7",+ "/Users/someone/Payroll/march.pdf",+ "boom"));++ assertThat(controller.list(null).notifications().getFirst().documentName()).isNull();+ verifyNoInteractions(storedFiles);+ }++ @Test+ void putsNoPartOfASourcePathInFrontOfAReader() {+ // Not the directory, not the account, not the filename - including for a team leader,+ // who reads rows that are not theirs.+ store.record(+ RecordFailure.forRun(+ FailureKind.UNKNOWN,+ TEAM,+ null,+ "policy-1",+ "run-1",+ "source-7",+ "/Users/someone/Private/Legal/settlement.pdf",+ "boom"));++ NotificationView notification = controller.list(null).notifications().getFirst();++ assertThat(notification.toString())+ .doesNotContain("Users", "Private", "Legal", "settlement");}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationResolveTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationResolveTest.javaindex b6cddd6a71..22a3246ebe 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationResolveTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/NotificationResolveTest.java@@ -22,6 +22,8 @@ import stirling.software.proprietary.notification.NotificationController;import stirling.software.proprietary.notification.NotificationService;import stirling.software.proprietary.notification.NotificationView;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.store.PolicyStore;+import stirling.software.proprietary.storage.repository.StoredFileRepository;/** Reporting a client-side retry that worked: the bell's one write. */@ExtendWith(MockitoExtension.class)@@ -36,6 +38,9 @@ class NotificationResolveTest {private FileRunEventStore store;private FileRunEventService failures;+ @Mock private PolicyStore policyStore;+ @Mock private StoredFileRepository storedFiles;+private NotificationController controller;@BeforeEach@@ -50,8 +55,9 @@ class NotificationResolveTest {List.of(new AcknowledgeAction(store), new DismissAction(store))),authority,userService,- props);- controller = new NotificationController(new NotificationService(failures));+ props,+ policyStore);+ controller = new NotificationController(new NotificationService(failures, storedFiles));lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);lenient().when(authority.canEditPolicies()).thenReturn(true);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.javaindex 3519344fd0..34c400c9d5 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java@@ -105,7 +105,8 @@ class PolicyFailureAttributionTest {List.of(new AcknowledgeAction(store), new DismissAction(store))),authority,userService,- props);+ props,+ policyStore);PolicyFailureRecorder recorder =new PolicyFailureRecorder(@@ -240,12 +241,15 @@ class PolicyFailureAttributionTest {class UnattendedSweep {@Test- void theRowIsRecordedWithNoActorWhileStillBillingTheOwner() throws Exception {+ void theRowIsRecordedAgainstTheSourcesOwnerWhileStillBillingThePolicysOwner()+ throws Exception {+ // Two different people on purpose: alice owns the policy and pays for the sweep, carol+ // owns the folder the documents came from and is the one who needs to hear about them.runAndFail(null, "src-watched-folder", "file-hash-1");assertThat(asReviewer("alice").actor())- .as("a trigger-fired run has no user to name")- .isNull();+ .as("an unattended run names the owner of the documents it pulled")+ .isEqualTo("carol");}@Test@@ -258,9 +262,9 @@ class PolicyFailureAttributionTest {}@Test- void aMemberDoesNotInheritAnUnattendedFailureAsTheirOwn() throws Exception {- // An unowned row must not fall to whoever happens to be reading: with no actor there is- // nothing for a member's narrowed read to match.+ void aMemberWhoOwnsNeitherTheSourceNorTheRunReadsNothing() throws Exception {+ // The narrowed read matches on the actor, so naming the source's owner hands the row to+ // that one person rather than to whoever happens to be reading.runAndFail(null, "src-watched-folder", "file-hash-1");assertThat(asMember("bob")).isNull();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.javaindex 2f17a04b84..876a52fe47 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java@@ -97,7 +97,8 @@ class PolicyFailureOwnershipTest {List.of(new AcknowledgeAction(store), new DismissAction(store))),authority,userService,- props);+ props,+ policyStore);PolicyFailureRecorder recorder =new PolicyFailureRecorder(@@ -247,22 +248,25 @@ class PolicyFailureOwnershipTest {class UnattendedSweep {@Test- void theRowIsOwnedByNobodySoTheReviewerInheritsTheOwnerActions() throws Exception {+ void theRowBelongsToWhoeverOwnsTheSourceRatherThanToNobody() throws Exception {+ // Nobody attended it, but the documents are still somebody's. Filed under no actor the+ // row reached a team leader and nobody else, never the person watching the folder.runAndFail(null, "src-watched-folder", "file-hash-1");- FileRunEvent unattended = asReviewer("alice");- assertThat(service.ownershipOf(unattended)).isEqualTo(Ownership.UNOWNED);- // No browser holds this document, so the offer is stated and disabled, not dropped.- assertThat(offeredTo(unattended)).contains(FailureActionId.VIEW_FILE);- assertThat(service.availableActions(unattended))- .filteredOn(action -> action.id() == FailureActionId.VIEW_FILE)- .singleElement()- .satisfies(- action -> {- assertThat(action.enabled()).isFalse();- assertThat(action.disabledReasonKey())- .isEqualTo("portal.failures.disabled.unattended");- });+ assertThat(service.ownershipOf(asMember("carol"))).isEqualTo(Ownership.MINE);+ }++ @Test+ void aReviewerWhoIsNotItsOwnerGetsTheReviewersActionsOnly() throws Exception {+ // The owner actions follow the owner. That is what keeps a leader from being offered+ // the button that runs a file in a folder belonging to someone else.+ runAndFail(null, "src-watched-folder", "file-hash-1");++ FileRunEvent theirs = asReviewer("alice");+ assertThat(service.ownershipOf(theirs)).isEqualTo(Ownership.THEIRS);+ assertThat(offeredTo(theirs))+ .contains(FailureActionId.VIEW_IN_PROCESSOR, FailureActionId.DISMISS)+ .doesNotContain(FailureActionId.VIEW_FILE, FailureActionId.OPEN_IN_TOOL);}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/RecordFailurePrivacyTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/RecordFailurePrivacyTest.javaindex c876644133..05ed5c681f 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/RecordFailurePrivacyTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/RecordFailurePrivacyTest.java@@ -43,16 +43,18 @@ class RecordFailurePrivacyTest {@Testvoid hasNoFileNameFieldAtAll() {- // Structural, not behavioural: if a fileName component is ever added back, this fails.+ // Structural, not behavioural: if a name component is ever added back, this fails. Not+ // NotificationView, whose documentName is derived per reader, never stored.assertThat(List.of(RecordFailure.class.getRecordComponents())).extracting(RecordComponent::getName)- .doesNotContain("fileName");+ .doesNotContain("fileName", "documentName");assertThat(List.of(FileRunEventEntity.class.getDeclaredFields())).extracting(Field::getName)- .doesNotContain("fileName");+ .doesNotContain("fileName", "documentName");+ // The portal's shape, read by reviewers over rows that are not theirs.assertThat(List.of(FileRunEventView.class.getRecordComponents())).extracting(RecordComponent::getName)- .doesNotContain("fileName");+ .doesNotContain("fileName", "documentName");}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/RetryInFolderActionTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/RetryInFolderActionTest.javanew file mode 100644index 0000000000..671b15474c--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/RetryInFolderActionTest.java@@ -0,0 +1,244 @@+package stirling.software.proprietary.failure;++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.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.util.List;+import java.util.Map;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Nested;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.engine.PolicyRunner;+import stirling.software.proprietary.policy.engine.SweepOutcome;+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.OutputSpec;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.store.PolicyStore;++/**+ * Tests for {@link RetryInFolderAction}, the one action that makes the server process a file for a+ * caller. Mostly about who may press it: a team leader reads rows they may not run.+ */+@ExtendWith(MockitoExtension.class)+class RetryInFolderActionTest {++ private static final String FOLDER_ID = "policy-folder-1";+ private static final String IDENTITY = "/Users/carol/Downloads/invoice.pdf";++ @Mock private PolicyStore policyStore;+ @Mock private PolicyAccessGuard policyAccessGuard;+ @Mock private ProcessedLedger processedLedger;+ @Mock private PolicyRunner policyRunner;+ @Mock private FileRunEventStore store;++ private RetryInFolderAction action;++ @BeforeEach+ void setUp() {+ action =+ new RetryInFolderAction(+ policyStore, policyAccessGuard, processedLedger, policyRunner, store);+ }++ private static Policy folder(String surface) {+ return new Policy(+ FOLDER_ID,+ "Downloads",+ "carol",+ true,+ false,+ "",+ List.of(),+ List.of(),+ OutputSpec.inline(),+ List.of(),+ 3L,+ null,+ surface,+ List.of());+ }++ private static FileRunEvent event(String policyId, String fileId) {+ return new FileRunEvent(+ "evt-1",+ 3L,+ "carol",+ FailureKind.UNKNOWN,+ FailureStage.INTERNAL,+ FailureSeverity.ERROR,+ FailureScope.RUN,+ FailureOrigin.POLICY,+ policyId,+ "run-1",+ "source-1",+ fileId,+ "boom",+ "dedup",+ 1,+ FileRunEventStatus.NEW,+ null,+ null,+ null,+ null);+ }++ @Nested+ @DisplayName("nobody runs a file in a folder that is not theirs")+ class Authorisation {++ @Test+ void refusesWhenTheGuardDoesNotGrantTheCallerThisFolder() {+ // The guard narrows a processing folder to its owner, so this is a leader reading a+ // colleague's row: visible to them, and not theirs to process.+ when(policyStore.get(FOLDER_ID))+ .thenReturn(java.util.Optional.of(folder(Policy.SURFACE_PROCESSING_FOLDER)));+ when(policyAccessGuard.canAccess(any(Policy.class))).thenReturn(false);++ assertThatThrownBy(() -> action.execute(event(FOLDER_ID, IDENTITY), Map.of(), "leader"))+ .isInstanceOf(FailureActionException.class);++ verifyNothingWasTouched();+ }++ @Test+ void refusesARowWhosePolicyIsNotAProcessingFolderAtAll() {+ // An org policy's runs are not a personal folder's, and its files are not addressed by+ // a ledger identity the presser owns.+ when(policyStore.get(FOLDER_ID))+ .thenReturn(java.util.Optional.of(folder(Policy.SURFACE_POLICY)));++ assertThatThrownBy(() -> action.execute(event(FOLDER_ID, IDENTITY), Map.of(), "carol"))+ .isInstanceOf(FailureActionException.class);++ verifyNothingWasTouched();+ }++ @Test+ void refusesARowThatNamesNoPolicy() {+ assertThatThrownBy(() -> action.execute(event(null, IDENTITY), Map.of(), "carol"))+ .isInstanceOf(FailureActionException.class);++ verifyNothingWasTouched();+ }++ @Test+ void answersAForeignFolderAndAMissingOneAlike() {+ // Otherwise the refusal tells a caller whether a folder id exists, which is a probe.+ when(policyStore.get(FOLDER_ID)).thenReturn(java.util.Optional.empty());++ assertThatThrownBy(() -> action.execute(event(FOLDER_ID, IDENTITY), Map.of(), "carol"))+ .isInstanceOf(FailureActionException.class)+ .extracting(e -> ((FailureActionException) e).getReason())+ .isEqualTo(FailureActionException.Reason.EVENT_NOT_FOUND);+ }++ private void verifyNothingWasTouched() {+ verify(processedLedger, never()).forgetFailure(anyString(), anyString());+ verify(policyRunner, never()).runFile(any(), anyString());+ }+ }++ @Nested+ @DisplayName("the owner's own folder")+ class Owner {++ @Test+ void runsOnlyTheFileTheRowNames() {+ when(policyStore.get(FOLDER_ID))+ .thenReturn(java.util.Optional.of(folder(Policy.SURFACE_PROCESSING_FOLDER)));+ when(policyAccessGuard.canAccess(any(Policy.class))).thenReturn(true);+ when(processedLedger.forgetFailure(FOLDER_ID, IDENTITY)).thenReturn(true);+ when(policyRunner.runFile(any(Policy.class), anyString())).thenReturn(oneRun());+ when(store.applyStatus(any(), any(), any(), any()))+ .thenReturn(mock(FileRunEvent.class));++ action.execute(event(FOLDER_ID, IDENTITY), Map.of("name", "../../etc/passwd"), "carol");++ // The identity comes from the row, so the inputs cannot redirect it at a sibling file.+ verify(policyRunner)+ .runFile(any(Policy.class), org.mockito.ArgumentMatchers.eq(IDENTITY));+ }++ @Test+ void leavesTheRowOpenAndParkedAgainWhenTheFolderYieldedNoRun() {+ // A paused or unreadable folder, or a file that has since left it, starts nothing.+ // Resolving anyway would make the failure vanish with nothing re-run, and leaving the+ // ledger row forgotten would have the next press answer "no parked failure".+ when(policyStore.get(FOLDER_ID))+ .thenReturn(java.util.Optional.of(folder(Policy.SURFACE_PROCESSING_FOLDER)));+ when(policyAccessGuard.canAccess(any(Policy.class))).thenReturn(true);+ when(processedLedger.statesFor(FOLDER_ID, List.of(IDENTITY)))+ .thenReturn(+ Map.of(+ IDENTITY,+ new ClaimState(ProcessedFileStatus.ERROR, "gate-1", "hash-1")));+ when(processedLedger.forgetFailure(FOLDER_ID, IDENTITY)).thenReturn(true);+ when(policyRunner.runFile(any(Policy.class), anyString())).thenReturn(noRuns());++ assertThatThrownBy(() -> action.execute(event(FOLDER_ID, IDENTITY), Map.of(), "carol"))+ .isInstanceOf(FailureActionException.class)+ .extracting(e -> ((FailureActionException) e).getReason())+ .isEqualTo(FailureActionException.Reason.NOTHING_TO_RUN);++ verify(processedLedger).settle(FOLDER_ID, IDENTITY, "gate-1", "hash-1", false);+ verify(store, never()).applyStatus(any(), any(), any(), any());+ }++ @Test+ void refusesWhenThereIsNoParkedFailureLeftToRun() {+ // Already retried, reverted, or swept: pressing again would claim work nobody asked to+ // redo.+ when(policyStore.get(FOLDER_ID))+ .thenReturn(java.util.Optional.of(folder(Policy.SURFACE_PROCESSING_FOLDER)));+ when(policyAccessGuard.canAccess(any(Policy.class))).thenReturn(true);+ when(processedLedger.forgetFailure(FOLDER_ID, IDENTITY)).thenReturn(false);++ assertThatThrownBy(() -> action.execute(event(FOLDER_ID, IDENTITY), Map.of(), "carol"))+ .isInstanceOf(FailureActionException.class);++ verify(policyRunner, never()).runFile(any(), anyString());+ }++ @Test+ void refusesARowThatNamesNoDocument() {+ when(policyStore.get(FOLDER_ID))+ .thenReturn(java.util.Optional.of(folder(Policy.SURFACE_PROCESSING_FOLDER)));+ when(policyAccessGuard.canAccess(any(Policy.class))).thenReturn(true);++ assertThatThrownBy(() -> action.execute(event(FOLDER_ID, null), Map.of(), "carol"))+ .isInstanceOf(FailureActionException.class);++ verify(processedLedger, never()).forgetFailure(anyString(), anyString());+ }+ }++ private static SweepOutcome oneRun() {+ return new SweepOutcome(List.of("run-2"), 1, 0, 0, 0, 0);+ }++ private static SweepOutcome noRuns() {+ return new SweepOutcome(List.of(), 0, 0, 0, 0, 0);+ }++ @Test+ void isTheServerHalfOfTheRetryTheBellOffers() {+ assertThat(action.id()).isEqualTo(FailureActionId.OPEN_IN_TOOL);+ assertThat(action.id().canRunOnServer()).isTrue();+ assertThat(action.id().executionFor(true)).isEqualTo(FailureActionId.Execution.SERVER);+ }+}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 bb2d8b3c9d..29e976e89f 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@@ -232,7 +232,7 @@ class PolicyControllerTest {}private static PolicyRunHandle handle(String runId) {- PolicyRun run = new PolicyRun(runId, null, definitionWithStep(), null, null, null);+ PolicyRun run = new PolicyRun(runId, null, definitionWithStep(), null, null, null, null);return new PolicyRunHandle(runId, CompletableFuture.completedFuture(run));}@@ -384,7 +384,8 @@ class PolicyControllerTest {@Test@DisplayName("returns the run view when present")void found() {- PolicyRun run = new PolicyRun("run-3", null, definitionWithStep(), null, null, null);+ PolicyRun run =+ new PolicyRun("run-3", null, definitionWithStep(), null, null, null, null);when(runRegistry.get("run-3")).thenReturn(run);when(jobOwnershipService.extractJobId("run-3")).thenReturn("run-3");when(jobOwnershipService.createScopedJobKey("run-3")).thenReturn("run-3");@@ -445,11 +446,14 @@ class PolicyControllerTest {@Test@DisplayName("excludes ad-hoc runs and runs owned by others")void filtersRuns() {- PolicyRun adHoc = new PolicyRun("adhoc", null, definitionWithStep(), null, null, null);+ PolicyRun adHoc =+ new PolicyRun("adhoc", null, definitionWithStep(), null, null, null, null);PolicyRun ownedStored =- new PolicyRun("owned", "policy-A", definitionWithStep(), null, null, null);+ new PolicyRun(+ "owned", "policy-A", definitionWithStep(), null, null, null, null);PolicyRun otherStored =- new PolicyRun("other", "policy-B", definitionWithStep(), null, null, null);+ new PolicyRun(+ "other", "policy-B", definitionWithStep(), null, null, null, null);when(runRegistry.all()).thenReturn(List.of(adHoc, ownedStored, otherStored));// ownedByCurrentUser: strip then re-apply scope reproduces the key only for the owneddiff --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 3ac6371e7c..23c5f6c850 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@@ -291,6 +291,7 @@ class PolicyEngineTest {org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard.class),+ org.mockito.Mockito.mock(PolicyFailureRecorder.class),mock(org.springframework.context.ApplicationEventPublisher.class));SweepOutcome outcome = runner.run(policy);@@ -306,7 +307,9 @@ class PolicyEngineTest {any(),eq(source.id()),anyString(),- isNull(),+ // The source's owner: nobody attended this, and the same person the+ // job was scoped to below is the one holding the documents.+ eq("source-owner"),anyString(),any(Throwable.class));}@@ -451,7 +454,7 @@ class PolicyEngineTest {any(),eq("src-s3-invoices"),eq("file-hash-1"),- isNull(),+ eq("carol"),anyString(),any(Throwable.class));}@@ -490,10 +493,10 @@ class PolicyEngineTest {}@Test- void anUnattendedFailureIsRecordedWithNoActorWhileStillBillingTheOwner() throws Exception {- // The two identities are deliberately different, and this pins both at once: usage is- // charged to the owner (MDC audit principal on the worker), but the failure has no actor,- // which is what makes it UNOWNED and hands the owner actions to the team's reviewer.+ void anUnattendedFailureIsFiledUnderTheDocumentsOwnerWhileStillBillingThePolicysOwner()+ throws Exception {+ // Two identities on purpose, pinned at once: usage is charged to the policy's owner (MDC+ // audit principal on the worker), the failure filed under whoever owns the document.when(toolMetadataService.isMultiInput(ROTATE)).thenReturn(false);String[] principalAtDispatch = {"<none>"};when(internalApiClient.post(eq(ROTATE), any()))@@ -527,7 +530,7 @@ class PolicyEngineTest {any(),eq("src-watched-folder"),eq("file-hash-1"),- isNull(),+ eq("carol"),anyString(),any(Throwable.class));}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.javaindex 692fe84c37..75a7c384b4 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java@@ -102,6 +102,7 @@ class PolicyRunRegistryTest {new PipelineDefinition(runId, List.of(), List.of()),null,null,+ null,null);registry.register(run);return run;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 1a9a76b1be..a0f9879ff0 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@@ -17,6 +17,7 @@ import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;import java.io.IOException;+import java.nio.file.NoSuchFileException;import java.util.List;import java.util.Map;import java.util.Set;@@ -37,6 +38,9 @@ import org.springframework.core.io.ByteArrayResource;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.UserServiceInterface;+import stirling.software.proprietary.failure.FailureKind;+import stirling.software.proprietary.failure.PolicyFailureRecorder;+import stirling.software.proprietary.policy.config.FolderAccessDeniedException;import stirling.software.proprietary.policy.config.PolicyAccessGuard;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;import stirling.software.proprietary.policy.input.FolderInputSource;@@ -93,6 +97,7 @@ class PolicyRunnerTest {new ApplicationProperties(),reachableOwners(),databaseLicenseGuard,+ mock(PolicyFailureRecorder.class),eventPublisher);}@@ -103,6 +108,149 @@ class PolicyRunnerTest {verifyNoInteractions(folderSource, policyEngine, processedLedger);}+ @Test+ void anUnreadableFolderIsRecordedForItsOwnerWithoutItsPath() throws Exception {+ // The detail is read by the whole team's reviewers, not only the folder's owner, and a+ // filesystem exception's message leads with the folder's location on the operator's disk.+ PolicyFailureRecorder recorder = mock(PolicyFailureRecorder.class);+ PolicyRunner recording =+ new PolicyRunner(+ policyEngine,+ List.of(folderSource),+ sourceStore,+ docCounter,+ processedLedger,+ new ApplicationProperties(),+ reachableOwners(),+ databaseLicenseGuard,+ recorder,+ eventPublisher);+ InputSpec spec = InputSpec.folder("/Users/carol/Payroll");+ Policy policy = policy(List.of(spec));+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any()))+ .thenThrow(+ new NoSuchFileException(+ "/Users/carol/Payroll", null, "input directory does not exist"));++ recording.run(policy);++ ArgumentCaptor<String> detail = ArgumentCaptor.forClass(String.class);+ verify(recorder)+ .recordRunFailureAs(+ eq(FailureKind.SOURCE_UNREADABLE),+ any(),+ eq("p1"),+ any(),+ eq("owner"),+ detail.capture());+ assertEquals("input directory does not exist", detail.getValue());+ assertFalse(detail.getValue().contains("/Users/carol"));+ }++ @Test+ void aFolderTheServerNoLongerPermitsIsRecordedWithoutNamingIt() throws Exception {+ // Locked down is one of the three ways a folder stops being readable, and the guard's own+ // message leads with the path, which is not for the team's reviewers to read.+ PolicyFailureRecorder recorder = mock(PolicyFailureRecorder.class);+ PolicyRunner recording =+ new PolicyRunner(+ policyEngine,+ List.of(folderSource),+ sourceStore,+ docCounter,+ processedLedger,+ new ApplicationProperties(),+ reachableOwners(),+ databaseLicenseGuard,+ recorder,+ eventPublisher);+ InputSpec spec = InputSpec.folder("/Users/carol/Payroll");+ Policy policy = policy(List.of(spec));+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any()))+ .thenThrow(+ new FolderAccessDeniedException(+ "/Users/carol/Payroll is outside policies.allowedFolderRoots"));++ recording.run(policy);++ ArgumentCaptor<String> detail = ArgumentCaptor.forClass(String.class);+ verify(recorder)+ .recordRunFailureAs(+ eq(FailureKind.SOURCE_UNREADABLE),+ any(),+ eq("p1"),+ any(),+ eq("owner"),+ detail.capture());+ assertFalse(detail.getValue().contains("/Users/carol"));+ }++ @Test+ void anUnreadableFolderIsFiledUnderTheSourcesOwnerNotThePolicys() throws Exception {+ // A team policy can be bound to a folder somebody else set up. The row goes to the person+ // who can fix the folder, as a document's failure in it would.+ PolicyFailureRecorder recorder = mock(PolicyFailureRecorder.class);+ PolicyRunner recording =+ new PolicyRunner(+ policyEngine,+ List.of(folderSource),+ sourceStore,+ docCounter,+ processedLedger,+ new ApplicationProperties(),+ reachableOwners(),+ databaseLicenseGuard,+ recorder,+ eventPublisher);+ InputSpec spec = InputSpec.folder("/Users/dave/Inbox");+ Source daves =+ sourceStore.save(+ new Source(null, "src", spec.type(), spec.options(), true, "dave", null));+ Policy policy = policyReferencing(List.of(daves.id()));+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any())).thenThrow(new IOException("mount gone"));++ recording.run(policy);++ verify(recorder)+ .recordRunFailureAs(+ eq(FailureKind.SOURCE_UNREADABLE),+ any(),+ eq("p1"),+ eq(daves.id()),+ eq("dave"),+ any());+ }++ @Test+ void aSourceThatBlowsUpIsNotCalledAnUnreadableFolder() throws Exception {+ // A bug in a source, or a bucket's SDK error, is a RuntimeException. Recording it would+ // tell the owner their folder cannot be read when nothing about the folder changed.+ PolicyFailureRecorder recorder = mock(PolicyFailureRecorder.class);+ PolicyRunner recording =+ new PolicyRunner(+ policyEngine,+ List.of(folderSource),+ sourceStore,+ docCounter,+ processedLedger,+ new ApplicationProperties(),+ reachableOwners(),+ databaseLicenseGuard,+ recorder,+ eventPublisher);+ InputSpec spec = InputSpec.folder("/Users/carol/Payroll");+ Policy policy = policy(List.of(spec));+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any())).thenThrow(new IllegalStateException("boom"));++ recording.run(policy);++ verifyNoInteractions(recorder);+ }+@Testvoid runsOnceWithNoFilesWhenThePolicyHasNoSources() {Policy policy = policy(List.of());@@ -134,6 +282,7 @@ class PolicyRunnerTest {org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard.class),+ org.mockito.Mockito.mock(PolicyFailureRecorder.class),eventPublisher);InputSpec spec = InputSpec.folder("/in");Policy policy = policy(List.of(spec));@@ -534,6 +683,7 @@ class PolicyRunnerTest {org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard.class),+ org.mockito.Mockito.mock(PolicyFailureRecorder.class),eventPublisher);for (String owner : new String[] {null, "", "deleted-user"}) {Source source =@@ -583,6 +733,7 @@ class PolicyRunnerTest {org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard.class),+ org.mockito.Mockito.mock(PolicyFailureRecorder.class),eventPublisher);SweepOutcome outcome = enforced.run(stranded.withSurface(Policy.SURFACE_PROCESSING_FOLDER));diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.javaindex 93242ccdb1..ea619e17db 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java@@ -34,6 +34,7 @@ import org.springframework.http.HttpStatus;import org.springframework.web.server.ResponseStatusException;import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.failure.PolicyFailureRecorder;import stirling.software.proprietary.policy.config.PolicyAccessGuard;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;import stirling.software.proprietary.policy.engine.PolicyEngine;@@ -159,6 +160,7 @@ class StorageFolderAuthorizationTest {properties,policies,mock(DatabaseLicenseGuard.class),+ mock(PolicyFailureRecorder.class),mock(org.springframework.context.ApplicationEventPublisher.class));}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.javaindex bce2eb1654..72afdfc6ce 100644--- 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.java@@ -16,7 +16,13 @@ class PolicyRunTest {private static PolicyRun run() {return new PolicyRun(- "run-1", "p1", new PipelineDefinition("t", List.of(), List.of()), null, null, null);+ "run-1",+ "p1",+ new PipelineDefinition("t", List.of(), List.of()),+ null,+ null,+ null,+ null);}@Test@@ -29,6 +35,7 @@ class PolicyRunTest {"copy", List.of(), List.of(OutputSpec.folder("/out"))),null,null,+ null,null);assertTrue(PolicyRunView.of(run).externalOutput());assertFalse(PolicyRunView.of(run()).externalOutput());@@ -56,6 +63,7 @@ class PolicyRunTest {destination))),null,null,+ null,null);assertEquals(!"inline".equals(destination.type()),diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.javaindex 015ff2a1d7..ad58a0ca61 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java@@ -19,7 +19,8 @@ class OutputDeliveryTest {new PipelineDefinition("test", List.of(), OutputSpec.inline()),source,document,- user);+ user,+ null);return OutputDelivery.forRun(run, PolicyInputs.of(List.of(new FileSystemResource(path))));}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.javaindex 191a3558f3..f2939d9ddc 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java@@ -23,6 +23,7 @@ import org.springframework.core.io.ByteArrayResource;import org.springframework.dao.DataAccessResourceFailureException;import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.failure.PolicyFailureRecorder;import stirling.software.proprietary.policy.config.PolicyAccessGuard;import stirling.software.proprietary.policy.engine.PolicyEngine;import stirling.software.proprietary.policy.engine.PolicyRunHandle;@@ -104,6 +105,7 @@ class StorageFolderTriggerTest {properties,mock(PolicyAccessGuard.class),mock(DatabaseLicenseGuard.class),+ mock(PolicyFailureRecorder.class),events);trigger = new StorageFolderTrigger(policies, sources, runner, properties);doAnswer(@@ -128,6 +130,7 @@ class StorageFolderTriggerTest {policy.toDefinition(),inv.<Source>getArgument(3).id(),identity,+ null,null);CompletableFuture<PolicyRun> completion = new CompletableFuture<>();Runnable finish =diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 7008964460..3a940819ce 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -5827,6 +5827,8 @@ label = "Free credits"adoptFailed = "The document was unlocked but could not be opened here. Try the tool directly."empty = "You're all caught up."handoffUnavailable = "This browser will not let the processor pass the document to the editor. Open it from the editor instead."+inSmartFolder = "This document is in a smart folder, so it is handled on the server rather than here."+inSmartFolderNamed = "{{name}} is in a smart folder, so it is handled on the server rather than here."noDocumentLinked = "This failure is not linked to a specific document, so it cannot be opened or retried here."notOnThisDevice = "This document is not on this device, so it cannot be opened or retried here."occurrences = "{{count}} times"@@ -5837,6 +5839,7 @@ repairedRerunNotAdopted = "The repaired document went through, but its result corepairedRerunUndelivered = "The document was repaired and the policy re-run started, but its result cannot be delivered here, so this failure stays open."rerunRejected = "The policy could not be run again just now. Try again in a moment."rerunUndelivered = "The policy re-run started, but its result cannot be delivered here, so this failure stays open."+retryInFolderFailed = "That document could not be run again just now."retryUnavailable = "This document can no longer be retried from this browser."title = "Notifications"unlockedNotRerun = "The document was unlocked and opened here, but the policy could not be run on it again."@@ -8494,6 +8497,10 @@ title = "File could not be repaired"description = "Your file is not a format this step can open, so the run could not read it."title = "Wrong file type"+[portal.failures.kind.sourceUnreadable]+description = "Your smart folder could not be read, so nothing in it was processed."+title = "Folder could not be read"+[portal.failures.kind.stepCannotRenderPage]description = "A page in your file could not be drawn, so the run could not finish."title = "Page could not be rendered"diff --git a/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx b/frontend/editor/src/core/components/notifications/NotificationBell.test.tsxindex 594b4b4413..0a481720d0 100644--- a/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx+++ b/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx@@ -68,7 +68,10 @@ vi.mock("@app/components/notifications/useNotificationsAvailable", () => ({}));// Core's own registry is empty, so without this there are no client actions to test.-vi.mock("@app/components/notifications/notificationActions", () => ({+vi.mock("@app/components/notifications/notificationActions", async () => ({+ ...(await vi.importActual<+ typeof import("@app/components/notifications/notificationActions")+ >("@app/components/notifications/notificationActions")),useNotificationActions: () => h.specs,}));@@ -141,6 +144,9 @@ function notification(defaultTitle: title,detail: "boom",fileId: "f-1",+ documentName: null,+ documentLocation: "BROWSER",+ heldByServer: false,sourceId: null,policyId: null,occurrences: 1,@@ -490,19 +496,24 @@ describe("NotificationBell", () => {).toBeTruthy();});- it("claims nothing about a device for a row it never looks up", async () => {- // Never on any device, so never probed, and an absent lookup is not an absent document.+ it("says where a server-held document is rather than that it is missing", async () => {+ // Never on any device, so never probed, and an absent lookup is not an absent document. "Not on+ // this device" would read as a fault in a folder working exactly as configured.h.hasLocalFile = false;fetchNotifications.mockResolvedValue([notification("a", "Password-protected document", {origin: "POLICY",- sourceId: "src-s3-invoices",+ sourceId: "src-downloads",+ documentLocation: "SMART_FOLDER",+ heldByServer: true,+ fileId: null,}),]);render(<NotificationBell />);await openPanel();expect(await screen.findByText("Password-protected document")).toBeTruthy();+ expect(screen.getByText(/is in a smart folder/)).toBeTruthy();expect(screen.queryByText(/not on this device|not linked to a specific document/,diff --git a/frontend/editor/src/core/components/notifications/NotificationItem.tsx b/frontend/editor/src/core/components/notifications/NotificationItem.tsxindex 634252d220..d4bfb5e3b7 100644--- a/frontend/editor/src/core/components/notifications/NotificationItem.tsx+++ b/frontend/editor/src/core/components/notifications/NotificationItem.tsx@@ -9,10 +9,11 @@ import {refreshNotificationsNow,} from "@app/hooks/useNotifications";import type { NotificationDocumentState } from "@app/hooks/useNotifications";-import type {- ClientActionRegistry,- ClientActionSpec,- NotificationActionContext,+import {+ closesPanelFor,+ type ClientActionRegistry,+ type ClientActionSpec,+ type NotificationActionContext,} from "@app/components/notifications/notificationActions";import { promoteActions } from "@app/components/notifications/notificationActionSlots";import type {@@ -53,6 +54,21 @@ function noteFor(});if (notification.ownership !== "MINE" || documentState.hasLocalFile)return null;+ // Said before the missing-document cases: this one is not missing, it is somewhere this browser+ // was never going to reach.+ if (notification.documentLocation === "SMART_FOLDER")+ return notification.documentName+ ? t("notifications.inSmartFolderNamed", {+ defaultValue:+ "{{name}} is in a smart folder, so it is handled on the server rather than here.",+ name: notification.documentName,+ })+ : t(+ "notifications.inSmartFolder",+ "This document is in a smart folder, so it is handled on the server rather than here.",+ );+ // A folder that could not be read names no document by design, so there is none to miss.+ if (!notification.fileId && notification.heldByServer) return null;if (!notification.fileId)return t("notifications.noDocumentLinked",@@ -142,7 +158,7 @@ export function NotificationItem({// without this the row a reader just fixed sits there until a poll happens to land. Re-read// rather than patched here, as the password path does: the server decides what closed.refreshNotificationsNow();- if (spec.closesPanel) onDismissPanel();+ if (closesPanelFor(spec, context)) onDismissPanel();};const copyDetail = async () => {diff --git a/frontend/editor/src/core/components/notifications/notificationActions.ts b/frontend/editor/src/core/components/notifications/notificationActions.tsindex 4492eca776..3e256659a6 100644--- a/frontend/editor/src/core/components/notifications/notificationActions.ts+++ b/frontend/editor/src/core/components/notifications/notificationActions.ts@@ -30,8 +30,20 @@ export interface ClientActionSpec {): ClientActionOutcome | void | Promise<ClientActionOutcome | void>;/** Collect a password before running. Never stored, never logged. */needsPassword?: boolean;- /** Whether the panel should get out of the way, the destination being behind it. */- closesPanel?: boolean;+ /**+ * Whether the panel should get out of the way, the destination being behind it. A function+ * answers per row, for an action that navigates for one document and stays put for another.+ */+ closesPanel?: boolean | ((context: NotificationActionContext) => boolean);+}++export function closesPanelFor(+ spec: ClientActionSpec,+ context: NotificationActionContext,+): boolean {+ return typeof spec.closesPanel === "function"+ ? spec.closesPanel(context)+ : Boolean(spec.closesPanel);}/** An id with no entry is skipped rather than rendered unwired. */diff --git a/frontend/editor/src/core/components/notifications/useNotificationPasswordPrompt.tsx b/frontend/editor/src/core/components/notifications/useNotificationPasswordPrompt.tsxindex b37d74733a..29deb82ac0 100644--- a/frontend/editor/src/core/components/notifications/useNotificationPasswordPrompt.tsx+++ b/frontend/editor/src/core/components/notifications/useNotificationPasswordPrompt.tsx@@ -2,6 +2,7 @@ import { useState } from "react";import { useTranslation } from "react-i18next";import EncryptedPdfUnlockModal from "@app/components/shared/EncryptedPdfUnlockModal";import { refreshNotificationsNow } from "@app/hooks/useNotifications";+import { closesPanelFor } from "@app/components/notifications/notificationActions";import type { PasswordPrompt } from "@app/components/notifications/NotificationItem";/**@@ -42,7 +43,7 @@ export function useNotificationPasswordPrompt(closePanel: () => void) {close();// The incident was resolved server-side, so the list is re-read rather than patched here.refreshNotificationsNow();- if (prompt.spec.closesPanel) closePanel();+ if (closesPanelFor(prompt.spec, prompt.context)) closePanel();};return {diff --git a/frontend/editor/src/core/hooks/useNotifications.test.ts b/frontend/editor/src/core/hooks/useNotifications.test.tsindex 5b99542f32..e34f6b613d 100644--- a/frontend/editor/src/core/hooks/useNotifications.test.ts+++ b/frontend/editor/src/core/hooks/useNotifications.test.ts@@ -66,6 +66,9 @@ function notification(defaultTitle: id,detail: "boom",fileId: "f-1",+ documentName: null,+ documentLocation: "BROWSER",+ heldByServer: false,sourceId: null,policyId: null,occurrences: 1,@@ -125,7 +128,9 @@ describe("useNotifications", () => {notification("unattended", {origin: "POLICY",sourceId: "src-s3-invoices",- fileId: "hashed-identity",+ documentLocation: "SMART_FOLDER",+ heldByServer: true,+ fileId: null,}),]),);@@ -167,15 +172,68 @@ describe("useNotifications", () => {expect(result.current.unreadCount).toBe(1);});- it("hides a member's unattended row even when its id happens to be stored here", async () => {- // Storage answering for a source-fed row's hash is a collision, not the document.+ it("still asks this device about a smart-folder policy the member ran from the editor", async () => {+ // The policy is a smart folder's, but the run was attended and the document is the browser's.+ // Only the server's word makes a row held by it; the policy's kind alone does not.+ hasLocalFile.mockResolvedValue(false);+ fetchNotifications.mockResolvedValue(+ feed(+ [+ notification("attended", {+ policyId: "folder-policy",+ documentLocation: "BROWSER",+ heldByServer: false,+ fileId: "elsewhere",+ }),+ ],+ false,+ ),+ );++ const { result } = renderHook(() => useNotifications());++ await waitFor(() => expect(hasLocalFile).toHaveBeenCalledWith("elsewhere"));+ await waitFor(() => expect(result.current.notifications).toHaveLength(0));+ });++ it("shows a member the rows a smart folder produced, which reach nobody else", async () => {+ // Their own folder, their own documents: hidden, the person who set it up hears nothing when it+ // stops working. Storage is never asked either: a hit on a server-side reference is a collision.hasLocalFile.mockResolvedValue(true);fetchNotifications.mockResolvedValue(feed([- notification("unattended", {- sourceId: "src-s3-invoices",- fileId: "collides-with-a-local-id",+ notification("smart-folder", {+ sourceId: "src-downloads",+ documentLocation: "SMART_FOLDER",+ heldByServer: true,+ fileId: null,+ }),+ ],+ false,+ ),+ );++ const { result } = renderHook(() => useNotifications());++ await waitFor(() => expect(result.current.notifications).toHaveLength(1));+ expect(result.current.notifications[0].id).toBe("smart-folder");+ expect(hasLocalFile).not.toHaveBeenCalled();+ });++ it("shows a member the row about their folder itself, which names no document at all", async () => {+ // An unreadable folder processes nothing, so there is no document row to carry the news. The+ // row is about the folder, and its owner is the one person it was recorded for.+ fetchNotifications.mockResolvedValue(+ feed(+ [+ notification("folder-unreadable", {+ kindId: "SOURCE_UNREADABLE",+ origin: "POLICY",+ sourceId: "src-downloads",+ documentLocation: "UNREACHABLE",+ heldByServer: true,+ fileId: null,}),],false,@@ -184,8 +242,9 @@ describe("useNotifications", () => {const { result } = renderHook(() => useNotifications());- await waitFor(() => expect(fetchNotifications).toHaveBeenCalled());- expect(result.current.notifications).toHaveLength(0);+ await waitFor(() => expect(result.current.notifications).toHaveLength(1));+ expect(result.current.notifications[0].id).toBe("folder-unreadable");+ expect(hasLocalFile).not.toHaveBeenCalled();});it("shows a reviewer both rows, document here or not", async () => {diff --git a/frontend/editor/src/core/hooks/useNotifications.ts b/frontend/editor/src/core/hooks/useNotifications.tsindex ea308dffb3..2cbcc8c439 100644--- a/frontend/editor/src/core/hooks/useNotifications.ts+++ b/frontend/editor/src/core/hooks/useNotifications.ts@@ -74,11 +74,19 @@ const NO_DOCUMENT: NotificationDocumentState = {};/**- * Whether this browser could resolve the document a row names. Two id spaces share `fileId`: an- * attended run reports the id its editor minted, a source-fed one a hash that was never on a device.+ * Whether this browser holds the document a row names, and so could run a fix over it. The server+ * says: a client inferring it from `sourceId` cannot see a smart folder's rows at all.*/export function isResolvableHere(notification: AppNotification): boolean {- return (notification.sourceId ?? null) === null;+ return notification.documentLocation === "BROWSER";+}++/**+ * Rows the server keeps on the reader's behalf. The server says which, so a smart-folder policy+ * run from the editor, whose document is this browser's, is not mistaken for one.+ */+function isHeldByServer(notification: AppNotification): boolean {+ return notification.heldByServer;}interface NotificationsSnapshot {@@ -155,15 +163,16 @@ async function read(forCycle: number): Promise<void> {if (forCycle !== cycle) return;const documents = Object.fromEntries(resolved);- // Presentation, not access: the server has already scoped these rows to the reader. Hidden- // because every offer a member gets needs the document, so the row would only say so.+ // Presentation, not access: the server has already scoped these rows to the reader. A member is+ // shown what they can act on, plus what the server holds for them and nobody else.const visible = viewerReviewsTeam? listed: listed.filter(// Asked, not left to the lookup missing: a hit on another id space would be a collision.(n) =>- isResolvableHere(n) &&- Boolean(n.fileId && documents[n.fileId]?.hasLocalFile),+ isHeldByServer(n) ||+ (isResolvableHere(n) &&+ Boolean(n.fileId && documents[n.fileId]?.hasLocalFile)),);// Per read, since signing in or out changes whose marker applies without remounting the bell.diff --git a/frontend/editor/src/core/services/notifications.ts b/frontend/editor/src/core/services/notifications.tsindex 70d86e676f..efebae452c 100644--- a/frontend/editor/src/core/services/notifications.ts+++ b/frontend/editor/src/core/services/notifications.ts@@ -15,6 +15,12 @@ export type NotificationOwnership = "MINE" | "THEIRS" | "UNOWNED";/** How much of the row an action has earned; `promoteActions` turns it into a place. */export type NotificationActionSlot = "RESOLUTION" | "SECONDARY" | "OVERFLOW";+/**+ * Where the document behind a row is. The server decides: this browser cannot tell a file id it+ * minted from a reference held on a server it has never seen.+ */+export type DocumentLocation = "BROWSER" | "SMART_FOLDER" | "UNREACHABLE";+/** `id` is an open string, not a union: the server may know actions this build does not. */export interface NotificationActionOffer {id: string;@@ -40,8 +46,16 @@ export interface AppNotification {titleKey: string;defaultTitle: string;detail: string | null;- /** Two id spaces share this field, and `sourceId` says which: see `isResolvableHere`. */+ /** Only ever an id this browser minted, so it needs no disambiguating: null otherwise. */fileId: string | null;+ /** What to call a document this browser does not hold. The owner's own files only. */+ documentName: string | null;+ documentLocation: DocumentLocation;+ /**+ * The server keeps this row for the reader: a smart folder's document, or the folder itself+ * when it could not be read. Shown to a member without a local file; never fixable here.+ */+ heldByServer: boolean;/** Which folder, bucket or webhook fed the run, and null for an attended one. */sourceId: string | null;policyId: string | null;@@ -99,3 +113,36 @@ export async function reportNotificationResolved(return false;}}++/**+ * Run one of a row's server-side actions. The reader pressed a button and is owed an answer, so a+ * refusal is reported rather than swallowed: null when it worked, the server's reason when not.+ */+export async function dispatchNotificationAction(+ notificationId: string,+ actionId: string,+): Promise<string | null> {+ try {+ await apiClient.post(+ `${NOTIFICATIONS_PATH}/${encodeURIComponent(notificationId)}/actions/${encodeURIComponent(actionId)}`,+ undefined,+ { suppressErrorToast: true },+ );+ return null;+ } catch (error) {+ const response = (+ error as {+ response?: {+ status?: number;+ data?: { detail?: string; title?: string };+ };+ }+ )?.response;+ // Ids and status only: the row's detail and document name stay out of the console.+ console.warn(+ `Notification action ${actionId} on ${notificationId} failed`,+ response?.status ?? "no response",+ );+ return response?.data?.detail ?? response?.data?.title ?? "";+ }+}diff --git a/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx b/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsxindex 32b5268f81..0dc2384392 100644--- a/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx+++ b/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx@@ -37,12 +37,15 @@ vi.mock("@app/services/notificationPolicyRetry", () => ({}));const reportNotificationResolved = vi.fn();+const dispatchNotificationAction = vi.fn();vi.mock("@app/services/notifications", async () => ({...(await vi.importActual<typeof import("@app/services/notifications")>("@app/services/notifications",)),reportNotificationResolved: (...args: unknown[]) =>reportNotificationResolved(...args),+ dispatchNotificationAction: (...args: unknown[]) =>+ dispatchNotificationAction(...args),}));const navigate = vi.fn();@@ -160,6 +163,7 @@ beforeEach(() => {// The adopted document's own id, not the reference the failure was filed against.addFiles.mockReset().mockResolvedValue([{ fileId: "f-unlocked" }]);reportNotificationResolved.mockReset().mockResolvedValue(true);+ dispatchNotificationAction.mockReset().mockResolvedValue(null);retryWithPassword.mockReset().mockResolvedValue({ ok: true, files: [] });// The unlock succeeds by default: most cases below are about what happens afterwards.unlockLocalDocument.mockReset().mockResolvedValue({@@ -592,3 +596,46 @@ describe("retrying an attended policy run", () => {expect(reportNotificationResolved).not.toHaveBeenCalled();});});++describe("OPEN_IN_TOOL for a smart folder's document", () => {+ const inFolder = () => ({+ notification: notification({+ kindId: "UNKNOWN",+ documentLocation: "SMART_FOLDER" as const,+ heldByServer: true,+ sourceId: "src-downloads",+ fileId: null,+ }),+ hasLocalFile: false,+ retryPayload: null,+ });++ it("is offered even though this browser holds nothing to open", () => {+ // The gap this test exists for: the same id opens a tool for a browser-held file, and would+ // be dropped for a folder's document if only that half were wired.+ expect(registry().OPEN_IN_TOOL?.available(inFolder())).toBe(true);+ });++ it("asks the server by the row's own prefixed id, under the one shared id", async () => {+ // The bell never holds a raw row id, so dispatching by anything else would 400.+ await registry().OPEN_IN_TOOL?.run(inFolder());++ expect(dispatchNotificationAction).toHaveBeenCalledWith(+ "failure:evt-1",+ "OPEN_IN_TOOL",+ );+ });++ it("reports the server's refusal rather than claiming it worked", async () => {+ dispatchNotificationAction.mockResolvedValue(+ "No smart folder to run this document in",+ );++ const outcome = await registry().OPEN_IN_TOOL?.run(inFolder());++ expect(outcome).toEqual({+ ok: false,+ message: "No smart folder to run this document in",+ });+ });+});diff --git a/frontend/editor/src/proprietary/components/notifications/notificationActions.ts b/frontend/editor/src/proprietary/components/notifications/notificationActions.tsindex 462c7a53d4..269202d78c 100644--- a/frontend/editor/src/proprietary/components/notifications/notificationActions.ts+++ b/frontend/editor/src/proprietary/components/notifications/notificationActions.ts@@ -14,8 +14,10 @@ import {PORTAL_REVIEW_PATH,} from "@app/routes/portalBasename";import { EDITOR_BASENAME } from "@app/routes/editorBasename";+import { HAS_PORTAL } from "@app/routes/hasPortal";import { fileStorage } from "@app/services/fileStorage";import { rerunPolicy } from "@app/services/notificationPolicyRetry";+import { dispatchNotificationAction } from "@app/services/notifications";import { isValidToolId, type ToolId } from "@app/types/toolId";import type { FileId } from "@app/types/file";import {@@ -28,6 +30,7 @@ import {unavailable,} from "@app/components/notifications/resolutions";import {+ closesPanelFor,type ClientActionOutcome,type ClientActionRegistry,type ClientActionSpec,@@ -35,6 +38,7 @@ import {} from "@core/components/notifications/notificationActions";export {+ closesPanelFor,type ClientActionOutcome,type ClientActionRegistry,type ClientActionSpec,@@ -203,11 +207,57 @@ export function useNotificationActions(): ClientActionRegistry {};const viewInProcessor: ClientActionSpec = {- available: () => true,+ // Desktop ships the app without the processor, so the destination is not routed there and+ // the button navigated to nothing.+ available: () => HAS_PORTAL,closesPanel: true,run: () => navigate(REVIEW_DESTINATION),};+ const heldByServer = (context: NotificationActionContext) =>+ context.notification.documentLocation === "SMART_FOLDER";++ // What the server does on this browser's behalf: the document is in a folder this browser+ // cannot reach, so all the client does is ask, and the row names which file it is about.+ const askTheServer = (+ actionId: string,+ whenItFails: string,+ ): ClientActionSpec => ({+ available: heldByServer,+ run: async (context): Promise<ClientActionOutcome | void> => {+ const refusal = await dispatchNotificationAction(+ context.notification.id,+ actionId,+ );+ if (refusal === null) return;+ // The server's own words where it gave any: only it knows why the folder refused.+ return { ok: false, message: refusal || whenItFails };+ },+ });++ // One id, run by whichever side holds the document: the server resolves it per row, and this+ // picks the half that can act.+ const rerunInFolder = askTheServer(+ "OPEN_IN_TOOL",+ t(+ "notifications.retryInFolderFailed",+ "That document could not be run again just now.",+ ),+ );+ const retry: ClientActionSpec = {+ available: (context) =>+ heldByServer(context)+ ? rerunInFolder.available(context)+ : openInTool.available(context),+ // The server's half changes nothing on screen to move to, so the panel stays and shows the+ // row leave the list; the client's half opens the tool behind it.+ closesPanel: (context) => !heldByServer(context),+ run: (context) =>+ heldByServer(context)+ ? rerunInFolder.run(context)+ : openInTool.run(context),+ };+const resolutions = Object.fromEntries(RESOLUTIONS.map((resolution) => [resolution.actionId,@@ -216,7 +266,7 @@ export function useNotificationActions(): ClientActionRegistry {);return {- OPEN_IN_TOOL: openInTool,+ OPEN_IN_TOOL: retry,...resolutions,VIEW_FILE: viewFile,VIEW_IN_PROCESSOR: viewInProcessor,diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/testSupport.tsx b/frontend/editor/src/proprietary/components/notifications/resolutions/testSupport.tsxindex 91e74b37c9..e9216a2e1e 100644--- a/frontend/editor/src/proprietary/components/notifications/resolutions/testSupport.tsx+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/testSupport.tsx@@ -25,6 +25,9 @@ export function notification(defaultTitle: "Password-protected document",detail: "The PDF Document is passworded",fileId: "f-1",+ documentName: null,+ documentLocation: "BROWSER",+ heldByServer: false,sourceId: null,policyId: null,occurrences: 3,diff --git a/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.ts b/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.tsindex 15108c0807..dd367b4d0f 100644--- a/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.ts+++ b/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.ts@@ -72,6 +72,9 @@ function policyRow(overrides: Partial<AppNotification> = {}): AppNotification {defaultTitle: "Password-protected document",detail: "The PDF Document is passworded",fileId: "f-locked",+ documentName: null,+ documentLocation: "BROWSER",+ heldByServer: false,sourceId: null,policyId: "pol-1",occurrences: 1,