#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
Preserve processing originals in .stirling with seven-day orphan cleanup (#8165)
Reece Browneb95a7127c315
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.javaindex 93d571bf2b..48908c992f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java@@ -1,6 +1,9 @@package stirling.software.proprietary.policy.controller;+import static java.nio.file.LinkOption.NOFOLLOW_LINKS;+import java.io.IOException;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;@@ -384,7 +387,6 @@ public class ProcessingFolderController {files.stream().map(f -> FolderIdentities.identity(canonicalDir, permitted, f)).toList());- Path originals = FolderOutputSink.originalsDir(canonicalDir);return files.stream().map(f ->@@ -393,8 +395,8 @@ public class ProcessingFolderController {states.get(FolderIdentities.identity(canonicalDir, permitted, f)),- Files.isRegularFile(- originals.resolve(f.getFileName().toString()))))+ FolderOutputSink.hasOriginal(+ canonicalDir, f.getFileName().toString()))).filter(Objects::nonNull).toList();} catch (IOException e) {@@ -572,8 +574,9 @@ public class ProcessingFolderController {@Operation(summary = "Restore a file's archived original",description =- "Moves the pre-processing original kept under .stirling/originals back"- + " over the processed file. The folder is paused first so"+ "Restores the pre-processing original kept under .stirling"+ + " over the processed file, retaining the backup for future restores."+ + " The folder is paused first so"+ " nothing claims the restored file, and its ledger row is"+ " forgotten — it reads as waiting until processing resumes."+ " Disk-backed folders only: storage-backed replacement keeps no"@@ -598,24 +601,29 @@ public class ProcessingFolderController {}try {Path canonicalDir = FolderIdentities.canonicalDir(permitted);- Path archived = FolderOutputSink.originalsDir(canonicalDir).resolve(name);- if (!Files.isRegularFile(archived)) {+ if (!FolderOutputSink.hasOriginal(canonicalDir, name)) {throw new ResponseStatusException(HttpStatus.CONFLICT, "'" + name + "' has no original to restore");}policy = pauseForRevert(policy);- // The per-row check below cannot see a run mid-delivery, so restore only once the- // machine is fully quiet.- if (!policyRunner.quiesced(policy.id())) {- throw new ResponseStatusException(- HttpStatus.CONFLICT,- "the folder is processing right now - try again shortly");- }- if (!restoreOriginal(policy, permitted, canonicalDir, name)) {- throw new ResponseStatusException(- HttpStatus.CONFLICT, "'" + name + "' is being processed right now");+ synchronized (FolderOutputSink.originalLock(canonicalDir)) {+ if (!FolderOutputSink.hasOriginal(canonicalDir, name)) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "'" + name + "' has no original to restore");+ }+ // The per-row check below cannot see a run mid-delivery, so restore only once the+ // machine is fully quiet.+ if (!policyRunner.quiesced(policy.id())) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT,+ "the folder is processing right now - try again shortly");+ }+ if (!restoreOriginal(policy, permitted, canonicalDir, name)) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "'" + name + "' is being processed right now");+ }+ return toMountedFile(target, null, true);}- return toMountedFile(target, null, false);} catch (IOException e) {throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Could not restore " + name + ": " + e.getMessage());@@ -630,9 +638,9 @@ public class ProcessingFolderController {summary = "Restore every archived original in the folder",description ="Resets the folder: pauses it, cancels its in-flight runs and waits for"- + " them to stop, moves each original kept under"- + " .stirling/originals back over its"- + " processed file, and forgets the whole processed history —"+ + " them to stop, copies each original kept under"+ + " .stirling back over its"+ + " processed file, retains the backups, and forgets the whole processed history —"+ " failed files included — so everything reads as waiting"+ " until it resumes. Only files of the watched directory itself"+ " are touched, and a file mid-run is skipped rather than"@@ -655,29 +663,22 @@ public class ProcessingFolderController {// Wait for claims to settle: clearing the ledger before that lets a late settle// re-add a row. A run that outruns this wait leaves its file skipped below.policyRunner.awaitQuiesce(policy.id(), Duration.ofSeconds(10));- List<String> names = List.of();- Path originals = FolderOutputSink.originalsDir(canonicalDir);- if (Files.isDirectory(originals)) {- try (Stream<Path> entries = Files.list(originals)) {- names =- entries.filter(Files::isRegularFile)- .map(entry -> entry.getFileName().toString())- .toList();- }- }- int restored = 0;- int skipped = 0;- for (String name : names) {- if (restoreOriginal(policy, permitted, canonicalDir, name)) {- restored++;- } else {- skipped++;+ synchronized (FolderOutputSink.originalLock(canonicalDir)) {+ List<String> names = FolderOutputSink.originalNames(canonicalDir);+ int restored = 0;+ int skipped = 0;+ for (String name : names) {+ if (restoreOriginal(policy, permitted, canonicalDir, name)) {+ restored++;+ } else {+ skipped++;+ }}+ // Done and failed rows alike go, so the folder reads as untouched work; only a+ // run that outran the quiesce can re-add a row.+ processedLedger.clearPolicy(policy.id());+ return new RevertAllOutcome(restored, skipped);}- // Done and failed rows alike go, so the folder reads as untouched work; only a- // run that outran the quiesce can re-add a row.- processedLedger.clearPolicy(policy.id());- return new RevertAllOutcome(restored, skipped);} catch (IOException e) {throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Could not restore originals: " + e.getMessage());@@ -695,8 +696,8 @@ public class ProcessingFolderController {}/**- * Move one archived original back and forget its ledger row so the file reads unprocessed.- * False when the file is mid-run or the name resolves outside the watched directory.+ * Restore the archived original without consuming it and forget its ledger row. False when the+ * file is mid-run or the name resolves outside the watched directory.*/private boolean restoreOriginal(Policy policy, Path permitted, Path canonicalDir, String name)throws IOException {@@ -704,17 +705,30 @@ public class ProcessingFolderController {if (!permitted.equals(target.getParent())) {return false;}- Path archived = FolderOutputSink.originalsDir(canonicalDir).resolve(name);+ Path archived = FolderOutputSink.originalPath(canonicalDir, name);+ if (!FolderOutputSink.hasOriginal(canonicalDir, name)) {+ throw new IOException("Original archive is not a regular file: " + archived);+ }String identity = FolderIdentities.identity(canonicalDir, permitted, target);ClaimState state = processedLedger.statesFor(policy.id(), List.of(identity)).get(identity);if (state != null && state.status() == ProcessedFileStatus.PROCESSING) {return false;}- Files.move(- archived,- target,- StandardCopyOption.ATOMIC_MOVE,- StandardCopyOption.REPLACE_EXISTING);+ FolderOutputSink.clearOriginalExpiry(canonicalDir, name);+ Path staging = FolderOutputSink.originalStagingDir(canonicalDir);+ Path pending = Files.createTempFile(staging, "restore-", ".tmp");+ try {+ try (InputStream original = Files.newInputStream(archived, NOFOLLOW_LINKS)) {+ Files.copy(original, pending, StandardCopyOption.REPLACE_EXISTING);+ }+ Files.move(+ pending,+ target,+ StandardCopyOption.ATOMIC_MOVE,+ StandardCopyOption.REPLACE_EXISTING);+ } finally {+ Files.deleteIfExists(pending);+ }processedLedger.forget(policy.id(), identity);return true;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.javaindex c5060b2b5a..b0fdeff820 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/FolderOutputSink.java@@ -1,7 +1,10 @@package stirling.software.proprietary.policy.output;+import static java.nio.file.LinkOption.NOFOLLOW_LINKS;+import java.io.IOException;import java.io.InputStream;+import java.nio.charset.StandardCharsets;import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.Path;@@ -11,8 +14,11 @@ import java.security.MessageDigest;import java.time.Duration;import java.time.Instant;import java.util.ArrayList;+import java.util.LinkedHashSet;import java.util.List;+import java.util.Locale;import java.util.UUID;+import java.util.stream.IntStream;import java.util.stream.Stream;import org.springframework.core.io.Resource;@@ -54,6 +60,9 @@ public class FolderOutputSink implements PolicyOutputSink {// Staging entries are renamed away within one delivery; anything older is a crash leftover.private static final Duration STALE_TMP_AGE = Duration.ofDays(1);+ private static final Object[] ORIGINAL_LOCKS =+ IntStream.range(0, 64).mapToObj(i -> new Object()).toArray();+ static final String MISSING_ORIGINAL_PREFIX = ".missing-original-";private final FolderAccessGuard accessGuard;private final ProcessedLedger processedLedger;@@ -79,8 +88,7 @@ public class FolderOutputSink implements PolicyOutputSink {Path targetDir = accessGuard.requirePermitted(directoryOf(spec));Files.createDirectories(targetDir);Path canonicalDir = FolderIdentities.canonicalDir(targetDir);- Path tmpDir = stirlingDir(canonicalDir).resolve("tmp");- Files.createDirectories(tmpDir);+ Path tmpDir = originalStagingDir(canonicalDir);sweepStaleTmp(tmpDir);boolean replace = Boolean.parseBoolean(String.valueOf(spec.options().get(REPLACE_OPTION)));@@ -129,7 +137,7 @@ public class FolderOutputSink implements PolicyOutputSink {/*** Stream the output to its staging path. For a recorded delivery (stored policy) the content* hash is digested in the same pass, so the ledger gets both version tiers without re-reading a- * possibly huge output; ad-hoc runs record nothing and skip the digest entirely.+ * possibly huge output.*/private static String stage(Resource resource, Path staged, boolean hashed) throws IOException {if (!hashed) {@@ -163,37 +171,9 @@ public class FolderOutputSink implements PolicyOutputSink {boolean replace)throws IOException {if (replace) {- Path target = dir.resolve(name);- // Archive before the ledger row flips DONE, so a restore that reads DONE finds the- // original safe, never mid-move.- Path archived = archiveOriginal(dir, target);- try {- if (delivery.policyId() != null) {- processedLedger.recordOutput(- delivery.policyId(), target.toString(), gate, contentHash);- }- Files.move(- staged,- target,- StandardCopyOption.ATOMIC_MOVE,- StandardCopyOption.REPLACE_EXISTING);- } catch (IOException | RuntimeException failed) {- if (archived != null) {- try {- Files.move(archived, target, StandardCopyOption.ATOMIC_MOVE);- } catch (IOException lost) {- log.warn(- "Replace of {} failed and its original could not be put back: {}",- target,- lost.getMessage());- }- }- if (delivery.policyId() != null) {- processedLedger.forgetOutput(delivery.policyId(), target.toString(), gate);- }- throw failed;+ synchronized (originalLock(dir)) {+ return replaceOriginal(delivery, dir, name, staged, gate, contentHash);}- return target;}while (true) {Path target = uniqueTarget(dir, name);@@ -213,22 +193,116 @@ public class FolderOutputSink implements PolicyOutputSink {}}- /** Where a directory's pre-processing originals are kept, beside the staging dir. */+ private Path replaceOriginal(+ OutputDelivery delivery,+ Path dir,+ String name,+ Path staged,+ String gate,+ String contentHash)+ throws IOException {+ Path target = dir.resolve(name);+ // Archive before the ledger row flips DONE, so a restore that reads DONE finds the+ // original safe, never mid-move.+ archiveOriginal(dir, target);+ try {+ if (delivery.policyId() != null) {+ processedLedger.recordOutput(+ delivery.policyId(), target.toString(), gate, contentHash);+ }+ Files.move(+ staged,+ target,+ StandardCopyOption.ATOMIC_MOVE,+ StandardCopyOption.REPLACE_EXISTING);+ } catch (IOException | RuntimeException failed) {+ if (delivery.policyId() != null) {+ processedLedger.forgetOutput(delivery.policyId(), target.toString(), gate);+ }+ throw failed;+ }+ return target;+ }++ /**+ * Serializes archive, restore and expiry within this JVM; callers supply a canonical directory.+ */+ public static Object originalLock(Path canonicalDir) {+ return ORIGINAL_LOCKS[Math.floorMod(canonicalDir.hashCode(), ORIGINAL_LOCKS.length)];+ }++ /** A returned or restored file starts a fresh retention period if it is deleted again. */+ public static void clearOriginalExpiry(Path dir, String name) throws IOException {+ Files.deleteIfExists(missingOriginalMarker(dir, name));+ }++ static Path missingOriginalMarker(Path dir, String name) {+ return metadataPath(dir, name, MISSING_ORIGINAL_PREFIX);+ }++ private static Path metadataPath(Path dir, String name, String prefix) {+ String key = java.io.File.separatorChar == '\\' ? name.toLowerCase(Locale.ROOT) : name;+ return originalsDir(dir)+ .resolve(prefix + UUID.nameUUIDFromBytes(key.getBytes(StandardCharsets.UTF_8)));+ }++ /** Originals are direct files here; subdirectories contain internal processing data. */public static Path originalsDir(Path dir) {- return dir.resolve(".stirling").resolve("originals");+ return dir.resolve(".stirling");}/**- * Where a same-name re-drop's original goes once the canonical slot is taken. A subdirectory,- * not a numbered sibling: a restore brings back every regular file directly under {@link- * #originalsDir}, so a sibling would be restored as a file the watched folder never held.- *- * <p>Canonical stays with the first original, which is wrong when the user replaced the file- * with a different document of the same name; telling that apart needs the previous output's- * content hash, which the next claim clears from the ledger row.+ * Resolves a single filename's original, including backups from the nested archive layout.+ * Callers must validate that name contains no path components.*/- private static Path supersededDir(Path dir) {- return originalsDir(dir).resolve("superseded");+ public static Path originalPath(Path dir, String name) {+ Path original = flatOriginalPath(dir, name);+ Path legacy = originalsDir(dir).resolve("originals").resolve(name);+ return Files.notExists(original, NOFOLLOW_LINKS) && !Files.notExists(legacy, NOFOLLOW_LINKS)+ ? legacy+ : original;+ }++ private static Path flatOriginalPath(Path dir, String name) {+ return originalsDir(dir).resolve(reservedName(name) ? ".original-" + name : name);+ }++ /** Only regular backups inside real archive directories are eligible for restore. */+ public static boolean hasOriginal(Path dir, String name) {+ Path archived = originalPath(dir, name);+ return Files.isDirectory(originalsDir(dir), NOFOLLOW_LINKS)+ && Files.isDirectory(archived.getParent(), NOFOLLOW_LINKS)+ && Files.isRegularFile(archived, NOFOLLOW_LINKS);+ }++ /** Lists restorable filenames, excluding staging files and nested backup history. */+ public static List<String> originalNames(Path dir) throws IOException {+ var names = new LinkedHashSet<String>();+ Path originals = originalsDir(dir);+ if (!Files.isDirectory(originals, NOFOLLOW_LINKS)) return List.of();+ for (Path archive : List.of(originals, originals.resolve("originals"))) {+ if (!Files.isDirectory(archive, NOFOLLOW_LINKS)) continue;+ try (Stream<Path> entries = Files.list(archive)) {+ entries.filter(path -> Files.isRegularFile(path, NOFOLLOW_LINKS))+ .map(FolderOutputSink::originalName)+ .filter(java.util.Objects::nonNull)+ .filter(name -> hasOriginal(dir, name))+ .forEach(names::add);+ }+ }+ return List.copyOf(names);+ }++ static String originalName(Path archived) {+ String name = archived.getFileName().toString();+ if (name.startsWith(".original-") && reservedName(name.substring(10))) {+ return name.substring(10);+ }+ return name.startsWith(".") ? null : name;+ }++ private static boolean reservedName(String name) {+ return "tmp".equalsIgnoreCase(name) || "originals".equalsIgnoreCase(name);}/**@@ -238,6 +312,9 @@ public class FolderOutputSink implements PolicyOutputSink {private static Path stirlingDir(Path dir) throws IOException {Path root = dir.resolve(".stirling");Files.createDirectories(root);+ if (!Files.isDirectory(root, NOFOLLOW_LINKS)) {+ throw new IOException("Original archive is not a directory: " + root);+ }try {Files.setAttribute(root, "dos:hidden", true);} catch (UnsupportedOperationException | IOException e) {@@ -246,34 +323,43 @@ public class FolderOutputSink implements PolicyOutputSink {return root;}- /**- * Move the target into {@code .stirling/originals} before a replace overwrites it, returning- * the archived path, or null when nothing is at the target. Throws if an existing target cannot- * be archived, so the caller aborts before overwriting and never destroys an unpreserved- * original. With the canonical slot already taken, the kept original stays there and this- * content goes to {@link #supersededDir}.- *- * <p>Plain move, not {@code ATOMIC_MOVE}: the archive is hidden under {@code .stirling} so- * needs no atomic visibility, and a plain move survives a cross-device archive dir where {@code- * ATOMIC_MOVE} would throw.- */- private static Path archiveOriginal(Path dir, Path target) throws IOException {- if (!Files.exists(target)) {- return null;+ /** Staging must stay inside the archive rather than follow a substituted directory link. */+ public static Path originalStagingDir(Path dir) throws IOException {+ Path staging = stirlingDir(dir).resolve("tmp");+ Files.createDirectories(staging);+ if (!Files.isDirectory(staging, NOFOLLOW_LINKS)) {+ throw new IOException("Original staging is not a directory: " + staging);+ }+ return staging;+ }++ private static void archiveOriginal(Path dir, Path target) throws IOException {+ clearOriginalExpiry(dir, target.getFileName().toString());+ if (Files.notExists(target, NOFOLLOW_LINKS)) {+ return;}stirlingDir(dir);- Path originals = originalsDir(dir);- Files.createDirectories(originals);String name = target.getFileName().toString();- Path archived = originals.resolve(name);- if (Files.exists(archived)) {- // Kept aside, so the overwrite cannot destroy this content either.- Path superseded = supersededDir(dir);- Files.createDirectories(superseded);- archived = uniqueTarget(superseded, name);+ Path existing = originalPath(dir, name);+ Path archived = flatOriginalPath(dir, name);+ if (!Files.notExists(existing, NOFOLLOW_LINKS)) {+ if (!hasOriginal(dir, name)) {+ throw new IOException("Original archive is not a regular file: " + existing);+ }+ if (!existing.equals(archived)) {+ Files.move(existing, archived, StandardCopyOption.ATOMIC_MOVE);+ }+ return;+ }+ // Keep the input in place until output publication succeeds; edits never replace this+ // backup.+ Path pending = Files.createTempFile(originalsDir(dir).resolve("tmp"), "original-", ".tmp");+ try {+ Files.copy(target, pending, StandardCopyOption.REPLACE_EXISTING);+ Files.move(pending, archived, StandardCopyOption.ATOMIC_MOVE);+ } finally {+ Files.deleteIfExists(pending);}- Files.move(target, archived);- return archived;}/** Best-effort removal of staging leftovers from crashed deliveries. */diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/ProcessingFolderOriginalCleanup.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/ProcessingFolderOriginalCleanup.javanew file mode 100644index 0000000000..a40b072cbf--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/ProcessingFolderOriginalCleanup.java@@ -0,0 +1,244 @@+package stirling.software.proprietary.policy.output;++import static java.nio.file.LinkOption.NOFOLLOW_LINKS;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.StandardOpenOption;+import java.nio.file.attribute.BasicFileAttributes;+import java.nio.file.attribute.FileTime;+import java.time.Duration;+import java.time.Instant;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.StringJoiner;+import java.util.TreeMap;+import java.util.regex.Pattern;+import java.util.stream.Collectors;+import java.util.stream.Stream;++import org.springframework.scheduling.annotation.Scheduled;+import org.springframework.stereotype.Service;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.policy.config.FolderAccessGuard;+import stirling.software.proprietary.policy.ledger.FolderIdentities;+import stirling.software.proprietary.policy.ledger.ProcessedFileStatus;+import stirling.software.proprietary.policy.ledger.ProcessedLedger;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.source.SourceStore;+import stirling.software.proprietary.policy.store.PolicyStore;++/**+ * Expires originals seven days after their files are first confirmed absent. Hidden marker files+ * persist that observation across restarts without changing the originals' timestamps. A complete+ * directory listing is required; unavailable folders and in-flight work never authorize deletion.+ */+@Service+@RequiredArgsConstructor+@Slf4j+public class ProcessingFolderOriginalCleanup {++ private static final Duration RETENTION = Duration.ofDays(7);+ private static final Pattern MISSING_MARKER =+ Pattern.compile(+ Pattern.quote(FolderOutputSink.MISSING_ORIGINAL_PREFIX)+ + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");++ private final PolicyStore policyStore;+ private final SourceStore sourceStore;+ private final FolderAccessGuard accessGuard;+ private final ProcessedLedger processedLedger;++ /** Pausing processing preserves the folder's ownership of its backups and their retention. */+ @Scheduled(fixedDelay = 300_000, initialDelay = 60_000)+ public void sweep() {+ sweep(Instant.now());+ }++ void sweep(Instant now) {+ Map<Path, Set<String>> directories = new HashMap<>();+ for (Policy policy : policyStore.all()) {+ if (Policy.SURFACE_PROCESSING_FOLDER.equals(policy.surface())) {+ for (String sourceId : policy.sourceIds()) {+ var source = sourceStore.get(sourceId).orElse(null);+ if (source != null && FolderAccessGuard.FOLDER_TYPE.equals(source.type())) {+ registerDirectory(+ directories, policy.id(), source.options().get("directory"));+ }+ }+ }+ if (policy.outputIds().isEmpty()) {+ registerOutput(directories, policy.id(), policy.output());+ }+ for (String outputId : policy.allOutputIds()) {+ sourceStore+ .get(outputId)+ .ifPresent(+ source ->+ registerOutput(+ directories, policy.id(), source.toOutputSpec()));+ }+ }+ for (var entry : directories.entrySet()) {+ try {+ synchronized (FolderOutputSink.originalLock(entry.getKey())) {+ reconcile(entry.getKey(), entry.getValue(), now);+ }+ } catch (IOException | RuntimeException e) {+ log.debug("Original cleanup deferred for {}: {}", entry.getKey(), e.getMessage());+ }+ }+ }++ private void registerOutput(+ Map<Path, Set<String>> directories, String policyId, OutputSpec output) {+ if (FolderAccessGuard.FOLDER_TYPE.equals(output.type())+ && Boolean.parseBoolean(String.valueOf(output.options().get("replace")))) {+ registerDirectory(directories, policyId, output.options().get("directory"));+ }+ }++ private void registerDirectory(+ Map<Path, Set<String>> directories, String policyId, Object value) {+ if (!(value instanceof String directory) || directory.isBlank()) return;+ try {+ Path permitted = accessGuard.requirePermitted(Path.of(directory));+ Path canonical = FolderIdentities.canonicalDir(permitted);+ directories.computeIfAbsent(canonical, ignored -> new HashSet<>()).add(policyId);+ } catch (IOException | RuntimeException e) {+ log.debug("Original cleanup cannot access {}: {}", directory, e.getMessage());+ }+ }++ private void reconcile(Path dir, Set<String> policyIds, Instant now) throws IOException {+ Set<String> present;+ try (Stream<Path> entries = Files.list(dir)) {+ present =+ entries.map(path -> path.getFileName().toString()).collect(Collectors.toSet());+ }+ Path workspace = FolderOutputSink.originalsDir(dir);+ if (!Files.isDirectory(workspace, NOFOLLOW_LINKS)) return;+ Map<String, List<Path>> originals = originals(workspace);+ Set<Path> markers = new HashSet<>();+ Set<String> processing =+ processingIdentities(+ policyIds,+ originals.keySet().stream()+ .map(name -> dir.resolve(name).toString())+ .toList());+ for (var entry : originals.entrySet()) {+ String name = entry.getKey();+ Path target = dir.resolve(name);+ Path marker = FolderOutputSink.missingOriginalMarker(dir, name);+ markers.add(marker);+ if (present.contains(name)+ || !Files.notExists(target, NOFOLLOW_LINKS)+ || processing.contains(target.toString())) {+ FolderOutputSink.clearOriginalExpiry(dir, name);+ continue;+ }+ String version = versionOf(workspace, entry.getValue());+ if (!Files.isRegularFile(marker, NOFOLLOW_LINKS)+ || !Files.readString(marker).equals(version)+ || Files.getLastModifiedTime(marker, NOFOLLOW_LINKS).toInstant().isAfter(now)) {+ Files.writeString(+ marker,+ version,+ StandardOpenOption.CREATE,+ StandardOpenOption.TRUNCATE_EXISTING,+ StandardOpenOption.WRITE,+ NOFOLLOW_LINKS);+ Files.setLastModifiedTime(marker, FileTime.from(now));+ continue;+ }+ Instant missingSince = Files.getLastModifiedTime(marker, NOFOLLOW_LINKS).toInstant();+ if (missingSince.isAfter(now.minus(RETENTION))) continue;+ if (!version.equals(versionOf(workspace, entry.getValue()))+ || !processingIdentities(policyIds, List.of(target.toString())).isEmpty()+ || !Files.notExists(target, NOFOLLOW_LINKS)) {+ FolderOutputSink.clearOriginalExpiry(dir, name);+ continue;+ }+ for (Path original : entry.getValue()) Files.deleteIfExists(original);+ Files.deleteIfExists(marker);+ }+ try (Stream<Path> entries = Files.list(workspace)) {+ for (Path marker :+ entries.filter(path -> Files.isRegularFile(path, NOFOLLOW_LINKS))+ .filter(+ path ->+ MISSING_MARKER+ .matcher(path.getFileName().toString())+ .matches())+ .filter(path -> !markers.contains(path))+ .toList()) {+ Files.deleteIfExists(marker);+ }+ }+ }++ private Set<String> processingIdentities(Set<String> policyIds, List<String> identities) {+ Set<String> processing = new HashSet<>();+ for (String policyId : policyIds) {+ processedLedger+ .statesFor(policyId, identities)+ .forEach(+ (identity, state) -> {+ if (state.status() == ProcessedFileStatus.PROCESSING)+ processing.add(identity);+ });+ }+ return processing;+ }++ private static Map<String, List<Path>> originals(Path workspace) throws IOException {+ Map<String, List<Path>> originals =+ java.io.File.separatorChar == '\\'+ ? new TreeMap<>(String.CASE_INSENSITIVE_ORDER)+ : new TreeMap<>();+ for (Path archive : List.of(workspace, workspace.resolve("originals"))) {+ if (!Files.isDirectory(archive, NOFOLLOW_LINKS)) continue;+ try (Stream<Path> entries = Files.list(archive)) {+ for (Path original :+ entries.filter(path -> Files.isRegularFile(path, NOFOLLOW_LINKS))+ .filter(path -> FolderOutputSink.originalName(path) != null)+ .toList()) {+ originals+ .computeIfAbsent(+ FolderOutputSink.originalName(original),+ ignored -> new ArrayList<>())+ .add(original);+ }+ }+ }+ return originals;+ }++ private static String versionOf(Path workspace, List<Path> originals) throws IOException {+ StringJoiner version = new StringJoiner("\n");+ for (Path original : originals) {+ BasicFileAttributes attributes =+ Files.readAttributes(original, BasicFileAttributes.class, NOFOLLOW_LINKS);+ version.add(+ workspace.relativize(original)+ + ":"+ + attributes.fileKey()+ + ":"+ + attributes.creationTime()+ + ":"+ + attributes.lastModifiedTime()+ + ":"+ + attributes.size());+ }+ return version.toString();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.javaindex 949c1ccbb8..524321075a 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java@@ -2,6 +2,7 @@ package stirling.software.proprietary.policy.controller;import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.junit.jupiter.api.Assumptions.assumeTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;@@ -15,6 +16,7 @@ import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;+import java.nio.file.FileSystemException;import java.nio.file.Files;import java.nio.file.Path;import java.time.LocalDateTime;@@ -54,6 +56,7 @@ import stirling.software.proprietary.policy.ledger.ProcessedLedger;import stirling.software.proprietary.policy.model.PipelineStep;import stirling.software.proprietary.policy.model.Policy;import stirling.software.proprietary.policy.model.RoutingRule;+import stirling.software.proprietary.policy.output.FolderOutputSink;import stirling.software.proprietary.policy.output.PolicyOutputSink;import stirling.software.proprietary.policy.output.StorageOutputSink;import stirling.software.proprietary.policy.source.InProcessSourceStore;@@ -849,7 +852,7 @@ class ProcessingFolderControllerTest {.thenAnswer(invocation -> invocation.getArgument(0));var view = controller.save(diskRequest()).getBody();Files.writeString(tempDir.resolve("doc.pdf"), "processed");- Path originals = tempDir.resolve(".stirling").resolve("originals");+ Path originals = tempDir.resolve(".stirling");Files.createDirectories(originals);Files.writeString(originals.resolve("doc.pdf"), "original");@@ -858,11 +861,17 @@ class ProcessingFolderControllerTest {view.id(), new ProcessingFolderController.RevertFileRequest("doc.pdf"));assertThat(Files.readString(tempDir.resolve("doc.pdf"))).isEqualTo("original");- assertThat(Files.exists(originals.resolve("doc.pdf"))).isFalse();+ assertThat(Files.readString(originals.resolve("doc.pdf"))).isEqualTo("original");assertThat(restored.state()).isEqualTo("waiting");+ assertThat(restored.hasOriginal()).isTrue();// Forgotten, not settled: the file reads as unprocessed until the folder resumes.verify(processedLedger).forget(eq(view.id()), anyString());assertThat(policyStore.get(view.id()).orElseThrow().enabled()).isFalse();+ Files.writeString(tempDir.resolve("doc.pdf"), "edited after restore");+ controller.revertFile(+ view.id(), new ProcessingFolderController.RevertFileRequest("doc.pdf"));+ assertThat(Files.readString(tempDir.resolve("doc.pdf"))).isEqualTo("original");+ assertThat(Files.readString(originals.resolve("doc.pdf"))).isEqualTo("original");}@Test@@ -883,13 +892,32 @@ class ProcessingFolderControllerTest {.hasMessageContaining("no original");}+ @ParameterizedTest+ @ValueSource(strings = {"tmp", "originals"})+ void revertRestoresEscapedInternalNames(String name) throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();+ Files.createDirectories(tempDir.resolve(".stirling/originals"));+ Files.createDirectories(tempDir.resolve(".stirling/tmp"));+ Path original = FolderOutputSink.originalPath(tempDir, name);+ Files.writeString(original, "original");+ Files.writeString(tempDir.resolve(name), "processed");++ controller.revertFile(view.id(), new ProcessingFolderController.RevertFileRequest(name));++ assertThat(Files.readString(tempDir.resolve(name))).isEqualTo("original");+ assertThat(Files.readString(original)).isEqualTo("original");+ }+@Testvoid revertAllRestoresEveryArchivedOriginal() throws Exception {lenient().when(folderAccessGuard.requirePermitted(any(Path.class))).thenAnswer(invocation -> invocation.getArgument(0));var view = controller.save(diskRequest()).getBody();- Path originals = tempDir.resolve(".stirling").resolve("originals");+ Path originals = tempDir.resolve(".stirling");Files.createDirectories(originals);for (String name : List.of("doc1.pdf", "doc2.pdf")) {Files.writeString(tempDir.resolve(name), "processed");@@ -902,7 +930,7 @@ class ProcessingFolderControllerTest {assertThat(outcome.skipped()).isZero();assertThat(Files.readString(tempDir.resolve("doc1.pdf"))).isEqualTo("original");assertThat(Files.readString(tempDir.resolve("doc2.pdf"))).isEqualTo("original");- assertThat(Files.exists(originals.resolve("doc1.pdf"))).isFalse();+ assertThat(Files.readString(originals.resolve("doc1.pdf"))).isEqualTo("original");assertThat(policyStore.get(view.id()).orElseThrow().enabled()).isFalse();verify(policyRunner).cancelRuns(view.id());verify(policyRunner).awaitQuiesce(eq(view.id()), any());@@ -911,33 +939,108 @@ class ProcessingFolderControllerTest {}@Test- void revertAllIgnoresNestedArchivesSoItRestoresOnlyTheFolderSOwnFiles() throws Exception {+ void revertAllRestoresBothLayoutsWithoutRestoringStagingOrExtraHistory() throws Exception {lenient().when(folderAccessGuard.requirePermitted(any(Path.class))).thenAnswer(invocation -> invocation.getArgument(0));var view = controller.save(diskRequest()).getBody();- Path originals = tempDir.resolve(".stirling").resolve("originals");- // The consumer half of the superseded layout: a same-name re-drop displaces the original- // it replaces one level down, and revert-all must leave it there. Restoring it as a- // sibling would leave the user a second "doc.pdf" their folder never held. The write half- // - that only the canonical name ever lands in this namespace - is pinned by- // FolderOutputSinkTest.aSupersededOriginalIsKeptOutOfTheRestoreNamespace.- Path superseded = originals.resolve("superseded");+ Path archive = tempDir.resolve(".stirling");+ Path legacy = archive.resolve("originals");+ Path superseded = legacy.resolve("superseded");+ Path staging = archive.resolve("tmp");Files.createDirectories(superseded);+ Files.createDirectories(staging);Files.writeString(tempDir.resolve("doc.pdf"), "processed");- Files.writeString(originals.resolve("doc.pdf"), "the-original");- Files.writeString(superseded.resolve("doc.pdf"), "displaced-original");+ Files.writeString(archive.resolve("doc.pdf"), "the-original");+ Files.writeString(legacy.resolve("old.pdf"), "legacy-original");+ Files.writeString(superseded.resolve("doc.pdf"), "extra-history");+ Files.writeString(staging.resolve("output.pdf"), "partial-output");var outcome = controller.revertAllFiles(view.id());- assertThat(outcome.restored()).isEqualTo(1);+ assertThat(outcome.restored()).isEqualTo(2);assertThat(Files.readString(tempDir.resolve("doc.pdf"))).isEqualTo("the-original");+ assertThat(Files.readString(tempDir.resolve("old.pdf"))).isEqualTo("legacy-original");try (Stream<Path> entries = Files.list(tempDir)) {assertThat(entries.filter(Files::isRegularFile).map(f -> f.getFileName().toString()))- .containsExactly("doc.pdf");+ .containsExactlyInAnyOrder("doc.pdf", "old.pdf");+ }+ assertThat(Files.readString(superseded.resolve("doc.pdf"))).isEqualTo("extra-history");+ assertThat(Files.readString(staging.resolve("output.pdf"))).isEqualTo("partial-output");+ }++ @Test+ void anExistingNestedOriginalIsStillListedAndRestorable() throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();+ Files.writeString(tempDir.resolve("doc.pdf"), "processed");+ Path original = tempDir.resolve(".stirling/originals/doc.pdf");+ Files.createDirectories(original.getParent());+ Files.writeString(original, "original");++ assertThat(controller.files(view.id()))+ .singleElement()+ .satisfies(file -> assertThat(file.hasOriginal()).isTrue());+ controller.revertFile(+ view.id(), new ProcessingFolderController.RevertFileRequest("doc.pdf"));++ assertThat(Files.readString(tempDir.resolve("doc.pdf"))).isEqualTo("original");+ assertThat(Files.readString(original)).isEqualTo("original");+ }++ @ParameterizedTest+ @ValueSource(strings = {"file", "legacyFile", "archive", "legacyDirectory"})+ void linkedOriginalsAreNeitherListedNorRestored(String linkType) throws Exception {+ lenient()+ .when(folderAccessGuard.requirePermitted(any(Path.class)))+ .thenAnswer(invocation -> invocation.getArgument(0));+ var view = controller.save(diskRequest()).getBody();+ Path target = tempDir.resolve("doc.pdf");+ Files.writeString(target, "processed");+ Path privateDir = Files.createDirectory(tempDir.resolve("private"));+ Path secret = Files.writeString(privateDir.resolve("doc.pdf"), "private contents");+ Path archive = tempDir.resolve(".stirling");+ Path link;+ Path source;+ if (linkType.equals("archive")) {+ link = archive;+ source = privateDir;+ } else {+ Files.createDirectory(archive);+ if (linkType.equals("legacyDirectory")) {+ link = archive.resolve("originals");+ source = privateDir;+ } else {+ Path parent =+ linkType.equals("legacyFile")+ ? Files.createDirectory(archive.resolve("originals"))+ : archive;+ link = parent.resolve("doc.pdf");+ source = secret;+ }+ }+ try {+ Files.createSymbolicLink(link, source);+ } catch (UnsupportedOperationException | FileSystemException e) {+ assumeTrue(false, "Symbolic links are unavailable: " + e.getMessage());}- // Still preserved, just not restored over anything.- assertThat(Files.readString(superseded.resolve("doc.pdf"))).isEqualTo("displaced-original");++ assertThat(controller.files(view.id()))+ .singleElement()+ .satisfies(file -> assertThat(file.hasOriginal()).isFalse());+ assertThat(FolderOutputSink.originalNames(tempDir)).isEmpty();+ assertThatThrownBy(+ () ->+ controller.revertFile(+ view.id(),+ new ProcessingFolderController.RevertFileRequest(+ "doc.pdf")))+ .isInstanceOf(ResponseStatusException.class);+ assertThat(controller.revertAllFiles(view.id()).restored()).isZero();+ assertThat(Files.readString(target)).isEqualTo("processed");+ assertThat(Files.readString(secret)).isEqualTo("private contents");}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.javaindex cd9bc89649..a71078d3ae 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/FolderOutputSinkTest.java@@ -4,6 +4,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.spy;import java.io.IOException;import java.nio.file.Files;@@ -15,6 +18,8 @@ import java.util.stream.Stream;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import org.springframework.core.env.StandardEnvironment;import org.springframework.core.io.ByteArrayResource;import org.springframework.core.io.Resource;@@ -50,7 +55,7 @@ class FolderOutputSinkTest {// exercise the allowlist, so they opt into login like a hosted install.properties.getSecurity().setEnableLogin(true);properties.getPolicies().setAllowedFolderRoots(List.of(tempDir.toString()));- ledger = new InProcessProcessedLedger();+ ledger = spy(new InProcessProcessedLedger());sink =new FolderOutputSink(new FolderAccessGuard(@@ -190,7 +195,7 @@ class FolderOutputSinkTest {}@Test- void replaceKeepsTheFirstOriginalForRevert() throws IOException {+ void reprocessingOurOutputKeepsTheOriginalAfterLedgerResetAndRestart() throws IOException {Path out = tempDir.resolve("out");Files.createDirectories(out);Files.writeString(out.resolve("a.pdf"), "original");@@ -198,22 +203,20 @@ class FolderOutputSinkTest {new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace);+ setUp();sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v2")), replace);assertEquals("v2", Files.readString(out.resolve("a.pdf")));// The archive holds what the user put in, not any intermediate result.- Path archived = out.resolve(".stirling").resolve("originals").resolve("a.pdf");+ Path archived = out.resolve(".stirling").resolve("a.pdf");assertEquals("original", Files.readString(archived));}@Testvoid archiveFailureAbortsTheReplaceInsteadOfDestroyingTheOriginal() throws IOException {Path out = tempDir.resolve("out");- Files.createDirectories(out.resolve(".stirling"));+ Files.createDirectories(out.resolve(".stirling").resolve("a.pdf"));Files.writeString(out.resolve("a.pdf"), "original");- // Block the originals dir by occupying its path with a regular file, so archiving throws- // exactly as an unwritable/locked/full originals dir would in the field.- Files.writeString(out.resolve(".stirling").resolve("originals"), "blocker");OutputSpec replace =new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));@@ -225,65 +228,109 @@ class FolderOutputSinkTest {}@Test- void aReDroppedSameNameFileKeepsItsOwnOriginalRatherThanLosingIt() throws IOException {+ void editingProcessedContentPreservesTheUploadedOriginal() throws IOException {Path out = tempDir.resolve("out");Files.createDirectories(out);Files.writeString(out.resolve("a.pdf"), "first-original");OutputSpec replace =new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));- sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed1")), replace);- // The user drops a genuinely different document under the same name; it is reprocessed.- Files.writeString(out.resolve("a.pdf"), "second-original");+ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "output-document")), replace);+ var outputTime = Files.getLastModifiedTime(out.resolve("a.pdf"));+ Files.writeString(out.resolve("a.pdf"), "annotated-output");+ Files.setLastModifiedTime(out.resolve("a.pdf"), outputTime);sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed2")), replace);assertEquals("processed2", Files.readString(out.resolve("a.pdf")));- Path originals = out.resolve(".stirling").resolve("originals");+ Path originals = out.resolve(".stirling");assertEquals("first-original", Files.readString(originals.resolve("a.pdf")));- // The second original was preserved, not overwritten away.- boolean kept;- try (Stream<Path> archived = Files.walk(originals)) {- kept =- archived.filter(Files::isRegularFile)- .anyMatch(- p -> {- try {- return "second-original".equals(Files.readString(p));- } catch (IOException e) {- return false;- }- });- }- assertTrue(kept, "the re-dropped original must be preserved, never silently lost");+ assertEquals(List.of("a.pdf"), FolderOutputSink.originalNames(out));+ assertFalse(Files.exists(originals.resolve("originals")));+ assertFalse(Files.exists(originals.resolve("superseded")));+ }++ @Test+ void reprocessingMigratesTheNestedOriginalWithoutChangingItsContents() throws IOException {+ Path out = tempDir.resolve("out");+ Path original = out.resolve(".stirling/originals/a.pdf");+ Files.createDirectories(original.getParent());+ Files.writeString(original, "first-original");+ Files.writeString(out.resolve("a.pdf"), "new-document");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed2")), replace);++ assertEquals("processed2", Files.readString(out.resolve("a.pdf")));+ assertEquals("first-original", Files.readString(out.resolve(".stirling/a.pdf")));+ assertFalse(Files.exists(original));+ assertFalse(Files.exists(original.getParent().resolve("superseded")));+ assertEquals(out.resolve(".stirling/a.pdf"), FolderOutputSink.originalPath(out, "a.pdf"));}@Test- void aSupersededOriginalIsKeptOutOfTheRestoreNamespace() throws IOException {+ void failedFirstDeliveryLeavesTheInputAndBackupIntact() throws IOException {Path out = tempDir.resolve("out");Files.createDirectories(out);- Files.writeString(out.resolve("a.pdf"), "first-original");+ Files.writeString(out.resolve("a.pdf"), "original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));+ doThrow(new IllegalStateException("ledger unavailable"))+ .when(ledger)+ .recordOutput(anyString(), anyString(), anyString(), anyString());++ assertThrows(+ IllegalStateException.class,+ () -> sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace));++ assertEquals("original", Files.readString(out.resolve("a.pdf")));+ assertEquals("original", Files.readString(out.resolve(".stirling/a.pdf")));+ }++ @Test+ void failedLaterDeliveryLeavesTheCurrentFileAndFirstOriginalIntact() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out);+ Files.writeString(out.resolve("a.pdf"), "original");OutputSpec replace =new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));+ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace);+ doThrow(new IllegalStateException("ledger unavailable"))+ .when(ledger)+ .recordOutput(anyString(), anyString(), anyString(), anyString());++ assertThrows(+ IllegalStateException.class,+ () -> sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v2")), replace));- sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed1")), replace);+ assertEquals("v1", Files.readString(out.resolve("a.pdf")));+ assertEquals("original", Files.readString(out.resolve(".stirling/a.pdf")));+ }++ @Test+ void editsAndFailedRetriesNeverOverwriteTheUploadedOriginal() throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out);+ Files.writeString(out.resolve("a.pdf"), "first-original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));+ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace);Files.writeString(out.resolve("a.pdf"), "second-original");- sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "processed2")), replace);+ doThrow(new IllegalStateException("ledger unavailable"))+ .doCallRealMethod()+ .when(ledger)+ .recordOutput(anyString(), anyString(), anyString(), anyString());- // A restore brings back every regular file directly under originals/, so only the- // canonical original may sit there; a sibling would be restored as a file the folder- // never held. The superseded one is kept, one level down.- Path originals = out.resolve(".stirling").resolve("originals");- List<String> restorable;- try (Stream<Path> entries = Files.list(originals)) {- restorable =- entries.filter(Files::isRegularFile)- .map(entry -> entry.getFileName().toString())- .toList();- }- assertEquals(List.of("a.pdf"), restorable);- assertEquals(- "second-original",- Files.readString(originals.resolve("superseded").resolve("a.pdf")));+ assertThrows(+ IllegalStateException.class,+ () -> sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v2")), replace));+ assertEquals("second-original", Files.readString(out.resolve("a.pdf")));+ assertEquals("first-original", Files.readString(out.resolve(".stirling/a.pdf")));++ sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v2")), replace);++ assertEquals("v2", Files.readString(out.resolve("a.pdf")));+ assertEquals("first-original", Files.readString(out.resolve(".stirling/a.pdf")));}@Test@@ -294,7 +341,27 @@ class FolderOutputSinkTest {sink.deliver(inPlaceRun("a.pdf"), List.of(named("a.pdf", "v1")), replace);- assertFalse(Files.exists(out.resolve(".stirling").resolve("originals").resolve("a.pdf")));+ assertFalse(Files.exists(out.resolve(".stirling").resolve("a.pdf")));+ }++ @ParameterizedTest+ @ValueSource(strings = {"tmp", "originals", "TMP", "Originals"})+ void internalDirectoryNamesHaveFlatRestorableBackups(String name) throws IOException {+ Path out = tempDir.resolve("out");+ Files.createDirectories(out.resolve(".stirling/originals"));+ Files.writeString(out.resolve(name), "original");+ OutputSpec replace =+ new OutputSpec("folder", Map.of("directory", out.toString(), "replace", true));++ sink.deliver(inPlaceRun(name), List.of(named(name, "processed")), replace);++ Path archived = FolderOutputSink.originalPath(out, name);+ assertEquals(out.resolve(".stirling"), archived.getParent());+ assertEquals("original", Files.readString(archived));+ assertEquals(List.of(name), FolderOutputSink.originalNames(out));+ assertEquals("processed", Files.readString(out.resolve(name)));+ assertTrue(Files.isDirectory(out.resolve(".stirling/tmp")));+ assertTrue(Files.isDirectory(out.resolve(".stirling/originals")));}@Test@@ -313,9 +380,7 @@ class FolderOutputSinkTest {// The watched file became its processed self; nothing landed beside it.assertEquals("v1", Files.readString(out.resolve("doc.pdf")));assertFalse(Files.exists(out.resolve("doc_redacted_watermarked.pdf")));- assertEquals(- "original",- Files.readString(out.resolve(".stirling").resolve("originals").resolve("doc.pdf")));+ assertEquals("original", Files.readString(out.resolve(".stirling").resolve("doc.pdf")));}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/ProcessingFolderOriginalCleanupTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/ProcessingFolderOriginalCleanupTest.javanew file mode 100644index 0000000000..124370265f--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/ProcessingFolderOriginalCleanupTest.java@@ -0,0 +1,322 @@+package stirling.software.proprietary.policy.output;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.attribute.FileTime;+import java.time.Duration;+import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.Optional;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.core.io.ByteArrayResource;+import org.springframework.core.io.FileSystemResource;++import stirling.software.proprietary.policy.config.FolderAccessGuard;+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.PipelineInput;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.policy.source.Source;+import stirling.software.proprietary.policy.source.SourceStore;+import stirling.software.proprietary.policy.store.PolicyStore;++class ProcessingFolderOriginalCleanupTest {+ private static final Instant START = Instant.parse("2026-09-01T12:00:00Z");++ @TempDir Path tempDir;+ private Path directory;+ private Policy policy;+ private final PolicyStore policies = mock(PolicyStore.class);+ private final SourceStore sources = mock(SourceStore.class);+ private final FolderAccessGuard guard = mock(FolderAccessGuard.class);+ private final InProcessProcessedLedger ledger = new InProcessProcessedLedger();+ private ProcessingFolderOriginalCleanup cleanup;++ @BeforeEach+ void setUp() throws Exception {+ directory = Files.createDirectory(tempDir.resolve("watched")).toRealPath();+ policy =+ new Policy(+ "p",+ "watched",+ null,+ false,+ List.of(PipelineInput.manual("s")),+ List.of(),+ OutputSpec.inline())+ .withSurface(Policy.SURFACE_PROCESSING_FOLDER);+ when(policies.all()).thenReturn(List.of(policy));+ when(sources.get("s"))+ .thenReturn(+ Optional.of(+ new Source(+ "s",+ "watched",+ "folder",+ Map.of("directory", directory.toString()),+ true,+ null,+ null)));+ when(guard.requirePermitted(any(Path.class))).thenAnswer(call -> call.getArgument(0));+ cleanup = new ProcessingFolderOriginalCleanup(policies, sources, guard, ledger);+ }++ @ParameterizedTest+ @ValueSource(strings = {"a.pdf", "originals/a.pdf"})+ void expiresBothLayoutsSevenDaysAfterObservedDeletionAcrossRestarts(String location)+ throws Exception {+ Path original = original(location);+ Files.setLastModifiedTime(original, FileTime.from(START.minus(Duration.ofDays(100))));++ cleanup.sweep(START);+ cleanup.sweep(START.plus(Duration.ofDays(7)).minusSeconds(1));+ assertThat(Files.exists(original)).isTrue();++ new ProcessingFolderOriginalCleanup(policies, sources, guard, ledger)+ .sweep(START.plus(Duration.ofDays(7)));++ assertThat(Files.exists(original)).isFalse();+ assertThat(Files.exists(marker())).isFalse();+ }++ @Test+ void aPresentFileNeverExpiresItsOriginal() throws Exception {+ Path original = original("a.pdf");+ Files.writeString(directory.resolve("a.pdf"), "processed");+ cleanup.sweep(START);+ cleanup.sweep(START.plus(Duration.ofDays(100)));+ assertThat(Files.readString(original)).isEqualTo("original");+ assertThat(Files.exists(marker())).isFalse();+ }++ @ParameterizedTest+ @ValueSource(strings = {"tmp", "originals"})+ void escapedNamesExpireOnlyAfterTheirActualFilesDisappear(String name) throws Exception {+ Files.createDirectories(directory.resolve(".stirling/originals"));+ Path original = FolderOutputSink.originalPath(directory, name);+ Files.writeString(original, "original");+ Path input = Files.writeString(directory.resolve(name), "processed");+ cleanup.sweep(START);+ cleanup.sweep(START.plus(Duration.ofDays(100)));+ assertThat(Files.exists(original)).isTrue();++ Files.delete(input);+ cleanup.sweep(START.plus(Duration.ofDays(101)));+ cleanup.sweep(START.plus(Duration.ofDays(108)));++ assertThat(Files.exists(original)).isFalse();+ assertThat(Files.isDirectory(directory.resolve(".stirling/originals"))).isTrue();+ }++ @Test+ void returningFilesResetTheGracePeriod() throws Exception {+ Path original = original("a.pdf");+ cleanup.sweep(START);+ Files.writeString(directory.resolve("a.pdf"), "returned");+ cleanup.sweep(START.plus(Duration.ofDays(6)));+ assertThat(Files.exists(marker())).isFalse();+ Files.delete(directory.resolve("a.pdf"));++ cleanup.sweep(START.plus(Duration.ofDays(8)));+ cleanup.sweep(START.plus(Duration.ofDays(14)));+ assertThat(Files.exists(original)).isTrue();+ cleanup.sweep(START.plus(Duration.ofDays(15)));+ assertThat(Files.exists(original)).isFalse();+ }++ @Test+ void reprocessingResetsExpiryEvenWithoutAnInterveningCleanupScan() throws Exception {+ Path original = original("a.pdf");+ cleanup.sweep(START);+ Path input = Files.writeString(directory.resolve("a.pdf"), "returned");+ new FolderOutputSink(guard, ledger)+ .deliver(+ new OutputDelivery(+ "run",+ "p",+ PolicyInputs.of(List.of(new FileSystemResource(input)))),+ List.of(new ByteArrayResource("processed".getBytes())),+ new OutputSpec(+ "folder",+ Map.of("directory", directory.toString(), "replace", true)));+ assertThat(Files.exists(marker())).isFalse();+ Files.delete(input);++ cleanup.sweep(START.plus(Duration.ofDays(8)));+ assertThat(Files.exists(original)).isTrue();+ cleanup.sweep(START.plus(Duration.ofDays(15)));+ assertThat(Files.exists(original)).isFalse();+ }++ @Test+ void inFlightFilesKeepTheirBackupsAndResetExpiry() throws Exception {+ Path original = original("a.pdf");+ cleanup.sweep(START);+ String identity = directory.resolve("a.pdf").toString();+ ledger.claim("p", identity, "gate", null);++ cleanup.sweep(START.plus(Duration.ofDays(8)));+ assertThat(Files.exists(original)).isTrue();+ assertThat(Files.exists(marker())).isFalse();+ ledger.forget("p", identity);+ cleanup.sweep(START.plus(Duration.ofDays(9)));+ assertThat(Files.exists(original)).isTrue();+ }++ @Test+ void anUnavailableFolderCannotAgeOrDeleteBackups() throws Exception {+ original("a.pdf");+ cleanup.sweep(START);+ Path offline = tempDir.resolve("offline");+ Files.move(directory, offline);+ Files.writeString(directory, "not a directory");++ cleanup.sweep(START.plus(Duration.ofDays(8)));++ assertThat(Files.readString(offline.resolve(".stirling/a.pdf"))).isEqualTo("original");+ Files.delete(directory);+ Files.move(offline, directory);+ Files.writeString(directory.resolve("a.pdf"), "returned");+ cleanup.sweep(START.plus(Duration.ofDays(9)));+ assertThat(Files.exists(marker())).isFalse();+ }++ @Test+ void deniedRootsCannotBeCleaned() throws Exception {+ Path original = original("a.pdf");+ cleanup.sweep(START);+ when(guard.requirePermitted(any(Path.class)))+ .thenThrow(new IllegalArgumentException("denied"));+ cleanup.sweep(START.plus(Duration.ofDays(8)));+ assertThat(Files.exists(original)).isTrue();+ }++ @Test+ void changedBackupsStartANewGracePeriod() throws Exception {+ Path original = original("a.pdf");+ cleanup.sweep(START);+ Files.writeString(original, "different original");+ cleanup.sweep(START.plus(Duration.ofDays(8)));+ assertThat(Files.exists(original)).isTrue();+ cleanup.sweep(START.plus(Duration.ofDays(15)));+ assertThat(Files.exists(original)).isFalse();+ }++ @Test+ void malformedMarkersRestartRetentionInsteadOfAuthorizingDeletion() throws Exception {+ Path original = original("a.pdf");+ Files.writeString(marker(), "interrupted metadata write");+ Files.setLastModifiedTime(marker(), FileTime.from(START.minus(Duration.ofDays(100))));+ cleanup.sweep(START);+ assertThat(Files.exists(original)).isTrue();+ assertThat(Files.getLastModifiedTime(marker()).toInstant()).isEqualTo(START);+ }++ @Test+ void ordinaryPoliciesAndRemovedProcessingFoldersDoNotAuthorizeCleanup() throws Exception {+ Path original = original("a.pdf");+ when(policies.all()).thenReturn(List.of(policy.withSurface(Policy.SURFACE_POLICY)));+ cleanup.sweep(START);+ assertThat(Files.exists(marker())).isFalse();+ when(policies.all()).thenReturn(List.of());+ cleanup.sweep(START.plus(Duration.ofDays(100)));+ assertThat(Files.exists(original)).isTrue();+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void teamPolicyReplacementOutputsReceiveRetention(boolean savedDestination) throws Exception {+ Path original = original("a.pdf");+ OutputSpec output =+ new OutputSpec(+ "folder", Map.of("directory", directory.toString(), "replace", true));+ Policy teamPolicy = policy.withSurface(Policy.SURFACE_POLICY).withOutput(output);+ if (savedDestination) {+ when(sources.get("output"))+ .thenReturn(+ Optional.of(+ new Source(+ "output",+ "Output",+ "folder",+ output.options(),+ false,+ null,+ 1L)));+ teamPolicy =+ teamPolicy.withOutput(OutputSpec.inline()).withOutputIds(List.of("output"));+ }+ when(policies.all()).thenReturn(List.of(teamPolicy));++ cleanup.sweep(START);+ cleanup.sweep(START.plus(Duration.ofDays(7)));++ assertThat(Files.exists(original)).isFalse();+ }++ @Test+ void teamPolicyOutputsRetainOriginalsWhileTheirFilesExist() throws Exception {+ Path original = original("a.pdf");+ when(policies.all())+ .thenReturn(+ List.of(+ policy.withSurface(Policy.SURFACE_POLICY)+ .withOutput(+ new OutputSpec(+ "folder",+ Map.of(+ "directory",+ directory.toString(),+ "replace",+ true)))));+ Files.writeString(directory.resolve("a.pdf"), "processed");++ cleanup.sweep(START);+ cleanup.sweep(START.plus(Duration.ofDays(100)));++ assertThat(Files.readString(original)).isEqualTo("original");+ assertThat(Files.exists(marker())).isFalse();+ }++ @Test+ void metadataIsExcludedFromRestoreAndRemovedWhenTheBackupDisappears() throws Exception {+ Path original = original("a.pdf");+ cleanup.sweep(START);+ assertThat(FolderOutputSink.originalNames(directory)).containsExactly("a.pdf");+ Files.delete(original);+ cleanup.sweep(START.plusSeconds(1));+ assertThat(Files.exists(marker())).isFalse();+ }++ @Test+ void stagingAndNestedHistoryAreNeverMistakenForOriginals() throws Exception {+ Path staged = original("tmp/staged.pdf");+ Path history = original("originals/superseded/a.pdf");+ cleanup.sweep(START);+ cleanup.sweep(START.plus(Duration.ofDays(100)));+ assertThat(Files.exists(staged)).isTrue();+ assertThat(Files.exists(history)).isTrue();+ }++ private Path original(String location) throws Exception {+ Path original = directory.resolve(".stirling").resolve(location);+ Files.createDirectories(original.getParent());+ return Files.writeString(original, "original");+ }++ private Path marker() {+ return FolderOutputSink.missingOriginalMarker(directory, "a.pdf");+ }+}diff --git a/frontend/editor/src-tauri/Cargo.lock b/frontend/editor/src-tauri/Cargo.lockindex ae74a6e2c4..cf58623d6f 100644--- a/frontend/editor/src-tauri/Cargo.lock+++ b/frontend/editor/src-tauri/Cargo.lock@@ -4657,6 +4657,7 @@ dependencies = ["tauri-plugin-store","tauri-plugin-updater","tauri-plugin-window-state",+ "tempfile","tiny_http","tokio","url",@@ -5394,9 +5395,9 @@ dependencies = [[[package]]name = "tempfile"-version = "3.26.0"+version = "3.27.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "82a72c767771b47409d2345987fda8628641887d5466101319899796367354a0"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand","getrandom 0.4.1",diff --git a/frontend/editor/src-tauri/Cargo.toml b/frontend/editor/src-tauri/Cargo.tomlindex 083dbe2be8..0507e4d8a1 100644--- a/frontend/editor/src-tauri/Cargo.toml+++ b/frontend/editor/src-tauri/Cargo.toml@@ -47,6 +47,7 @@ urlencoding = "2.1"sha2 = "0.11"base64 = "0.23"rand = "0.10"+tempfile = "3.27"[target.'cfg(target_os = "macos")'.dependencies]core-foundation = "0.10"diff --git a/frontend/editor/src-tauri/capabilities/default.json b/frontend/editor/src-tauri/capabilities/default.jsonindex 9a688d75e9..d630706a1a 100644--- a/frontend/editor/src-tauri/capabilities/default.json+++ b/frontend/editor/src-tauri/capabilities/default.json@@ -53,6 +53,10 @@"identifier": "fs:allow-stat","allow": [{ "path": "**" }]},+ {+ "identifier": "fs:allow-lstat",+ "allow": [{ "path": "**" }]+ },{"identifier": "fs:allow-mkdir","allow": [{ "path": "**" }]@@ -61,6 +65,10 @@"identifier": "fs:allow-write-file","allow": [{ "path": "**" }]},+ {+ "identifier": "fs:allow-exists",+ "allow": [{ "path": "**" }]+ },{"identifier": "fs:allow-rename","allow": [{ "path": "**" }]diff --git a/frontend/editor/src-tauri/src/commands/files.rs b/frontend/editor/src-tauri/src/commands/files.rsindex 5acc8d51f5..efaa690d84 100644--- a/frontend/editor/src-tauri/src/commands/files.rs+++ b/frontend/editor/src-tauri/src/commands/files.rs@@ -162,6 +162,32 @@ pub fn file_disk_state(path: String) -> DiskFileState {}}+/// Publishes a completed staging file beside its destination without replacing an existing entry.+/// Staging is consumed on success and discarded on failure; the destination is never overwritten.+#[tauri::command]+pub fn publish_processing_file(temporary: String, path: String) -> Result<(), String> {+ publish_processing_file_at(Path::new(&temporary), Path::new(&path))+ .map_err(|error| error.to_string())+}++fn publish_processing_file_at(temporary: &Path, path: &Path) -> std::io::Result<()> {+ let invalid =+ || std::io::Error::new(ErrorKind::InvalidInput, "Invalid processing staging file");+ let source_parent = temporary.parent().ok_or_else(invalid)?.canonicalize()?;+ let target_parent = path.parent().ok_or_else(invalid)?.canonicalize()?;+ if source_parent != target_parent+ || temporary+ .extension()+ .map_or(true, |extension| extension != "tmp")+ || !std::fs::symlink_metadata(temporary)?.file_type().is_file()+ {+ return Err(invalid());+ }+ tempfile::TempPath::try_from_path(temporary)?+ .persist_noclobber(path)+ .map_err(|error| error.error)+}+#[cfg(test)]mod tests {use super::*;@@ -177,6 +203,63 @@ mod tests {file_disk_state(path.to_string_lossy().to_string())}+ #[test]+ fn publication_preserves_the_first_complete_original() {+ let dir = temp_dir("publish_original");+ let staging = dir.join("original.tmp");+ let original = dir.join("original.pdf");+ std::fs::write(&staging, b"first original").unwrap();+ publish_processing_file_at(&staging, &original).unwrap();+ std::fs::write(&staging, b"processed bytes").unwrap();++ assert_eq!(+ publish_processing_file_at(&staging, &original)+ .unwrap_err()+ .kind(),+ ErrorKind::AlreadyExists+ );+ assert_eq!(std::fs::read(&original).unwrap(), b"first original");+ assert!(!staging.exists());+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn publication_respects_the_filesystems_case_equivalence() {+ let dir = temp_dir("publish_case");+ let staging = dir.join("original.tmp");+ let original = dir.join("Original.pdf");+ let alias = dir.join("original.pdf");+ std::fs::write(&original, b"first original").unwrap();+ std::fs::write(&staging, b"later bytes").unwrap();+ let case_insensitive = alias.exists();++ let result = publish_processing_file_at(&staging, &alias);++ if case_insensitive {+ assert_eq!(result.unwrap_err().kind(), ErrorKind::AlreadyExists);+ } else {+ result.unwrap();+ }+ assert_eq!(std::fs::read(&original).unwrap(), b"first original");+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn publication_rejects_a_different_destination_directory() {+ let dir = temp_dir("publish_outside");+ let staging = dir.join("original.tmp");+ let subdir = dir.join("other");+ std::fs::create_dir(&subdir).unwrap();+ std::fs::write(&staging, b"original").unwrap();+ assert_eq!(+ publish_processing_file_at(&staging, &subdir.join("original.pdf"))+ .unwrap_err()+ .kind(),+ ErrorKind::InvalidInput+ );+ std::fs::remove_dir_all(dir).unwrap();+ }+#[test]fn a_real_file_reports_its_size_and_mtime() {let dir = temp_dir("present");diff --git a/frontend/editor/src-tauri/src/lib.rs b/frontend/editor/src-tauri/src/lib.rsindex 8a4d9d38f2..661eeff7e8 100644--- a/frontend/editor/src-tauri/src/lib.rs+++ b/frontend/editor/src-tauri/src/lib.rs@@ -227,6 +227,7 @@ pub fn run() {pop_opened_files,clear_opened_files,file_disk_state,+ commands::files::publish_processing_file,watch_disk_paths,unwatch_disk_paths,open_in_new_window,diff --git a/frontend/editor/src/desktop/services/localProcessingDelivery.test.ts b/frontend/editor/src/desktop/services/localProcessingDelivery.test.tsindex 5fc706d48d..89971c4394 100644--- a/frontend/editor/src/desktop/services/localProcessingDelivery.test.ts+++ b/frontend/editor/src/desktop/services/localProcessingDelivery.test.ts@@ -1,14 +1,23 @@import { beforeEach, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({stat: vi.fn(),+ lstat: vi.fn(),+ invoke: vi.fn(),+ diskState: vi.fn(),writeFile: vi.fn(),rename: vi.fn(),remove: vi.fn(),+ mounted: vi.fn(),}));vi.mock("@tauri-apps/plugin-fs", () => ({ ...mocks, mkdir: vi.fn() }));+vi.mock("@tauri-apps/api/core", () => ({ invoke: mocks.invoke }));+vi.mock("@app/services/desktopFileLink", () => ({+ getDiskFileState: mocks.diskState,+}));vi.mock("@app/services/localFolderContents", () => ({readDiskFile: vi.fn(),writeDiskFile: vi.fn(),+ isWithinMount: mocks.mounted,}));vi.mock("@app/services/diskFileSync", () => ({beginSelfWrite: vi.fn(),@@ -17,6 +26,10 @@ vi.mock("@app/services/diskFileSync", () => ({import {replaceProcessingFile,sameProcessingFile,+ archiveProcessingInput,+ restoreProcessingFile,+ removeProcessingOutput,+ readProcessingOriginal,} from "@app/services/localProcessingDelivery";const input = {@@ -28,9 +41,168 @@ const input = {beforeEach(() => {vi.resetAllMocks();mocks.stat.mockResolvedValue({ size: 10, mtime: new Date(1000) });+ mocks.lstat.mockResolvedValue({+ isDirectory: true,+ isFile: true,+ isSymlink: false,+ });+ mocks.diskState.mockImplementation(async (path) =>+ path.includes("/.stirling/")+ ? { availability: "gone" }+ : { availability: "present", size: 10, modifiedMs: 1000 },+ );+ mocks.invoke.mockResolvedValue(undefined);mocks.writeFile.mockResolvedValue(undefined);mocks.rename.mockResolvedValue(undefined);mocks.remove.mockResolvedValue(undefined);+ mocks.mounted.mockResolvedValue(true);+ const pending = new Map<string, Promise<unknown>>();+ Object.defineProperty(navigator, "locks", {+ configurable: true,+ value: {+ request: (name: string, callback: () => Promise<unknown>) => {+ const next = (pending.get(name) ?? Promise.resolve())+ .catch(() => {})+ .then(callback);+ pending.set(name, next);+ return next;+ },+ },+ });+});++test("the original is stored directly under .stirling with its own filename", async () => {+ const file = new File(["original"], "a.pdf");+ vi.spyOn(file, "arrayBuffer").mockResolvedValue(+ new TextEncoder().encode("original").buffer,+ );+ expect(await archiveProcessingInput("/downloads", file)).toBe(+ "/downloads/.stirling/a.pdf",+ );+ expect(mocks.writeFile).toHaveBeenCalledWith(+ expect.stringContaining("/downloads/.stirling/.original-"),+ expect.any(Uint8Array),+ { createNew: true },+ );+ expect(Array.from(mocks.writeFile.mock.calls[0][1])).toEqual(+ Array.from(new TextEncoder().encode("original")),+ );+ expect(mocks.writeFile).toHaveBeenCalledBefore(mocks.invoke);+ expect(mocks.invoke).toHaveBeenCalledWith("publish_processing_file", {+ temporary: mocks.writeFile.mock.calls[0][0],+ path: "/downloads/.stirling/a.pdf",+ });+ expect(mocks.rename).not.toHaveBeenCalled();+});++test("an existing original is reused without writing another copy", async () => {+ mocks.diskState.mockResolvedValue({+ availability: "present",+ size: 10,+ modifiedMs: 1000,+ });+ mocks.stat.mockResolvedValue({ isFile: true });+ expect(+ await archiveProcessingInput("/downloads", new File(["later"], "a.pdf")),+ ).toBe("/downloads/.stirling/a.pdf");+ expect(mocks.writeFile).not.toHaveBeenCalled();+});++test("changed content cannot overwrite an existing original", async () => {+ mocks.diskState.mockResolvedValue({+ availability: "present",+ size: 10,+ modifiedMs: 1000,+ });+ mocks.stat.mockResolvedValue({+ isFile: true,+ size: 10,+ mtime: new Date(1000),+ });+ const file = new File(["new document"], "a.pdf");+ vi.spyOn(file, "arrayBuffer").mockResolvedValue(+ new TextEncoder().encode("new document").buffer,+ );++ expect(await archiveProcessingInput("/downloads", file)).toBe(+ "/downloads/.stirling/a.pdf",+ );+ expect(mocks.writeFile).not.toHaveBeenCalled();+ expect(mocks.rename).not.toHaveBeenCalled();+});++test("an unreadable original blocks processing instead of replacing the backup", async () => {+ mocks.diskState.mockResolvedValue({+ availability: "present",+ size: 10,+ modifiedMs: 1000,+ });+ mocks.lstat+ .mockResolvedValueOnce({ isDirectory: true })+ .mockRejectedValueOnce(new Error("Permission denied"));++ await expect(+ archiveProcessingInput("/downloads", new File(["new"], "a.pdf")),+ ).rejects.toThrow("Permission denied");++ expect(mocks.writeFile).not.toHaveBeenCalled();+ expect(mocks.rename).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalledWith("/downloads/.stirling/a.pdf");+});++test("an incomplete backup is removed so a retry can archive the input", async () => {+ mocks.writeFile.mockRejectedValueOnce(new Error("Disk full"));+ await expect(+ archiveProcessingInput("/downloads", new File(["input"], "a.pdf")),+ ).rejects.toThrow("Disk full");+ expect(mocks.rename).not.toHaveBeenCalled();+ expect(mocks.remove).toHaveBeenCalledWith(mocks.writeFile.mock.calls[0][0]);+ expect(mocks.remove).not.toHaveBeenCalledWith("/downloads/.stirling/a.pdf");+});++test("a backup created concurrently is never removed", async () => {+ mocks.invoke.mockRejectedValueOnce(new Error("File exists"));+ await expect(+ archiveProcessingInput("/downloads", new File(["input"], "a.pdf")),+ ).rejects.toThrow("File exists");+ expect(mocks.rename).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalledWith("/downloads/.stirling/a.pdf");+});++test("concurrent archive requests publish only the first original", async () => {+ const published = new Set<string>();+ mocks.diskState.mockImplementation(async (path) =>+ published.has(path)+ ? { availability: "present", size: 10, modifiedMs: 1000 }+ : { availability: "gone" },+ );+ mocks.stat.mockResolvedValue({ isFile: true });+ mocks.invoke.mockImplementation(async (_command, { path }) => {+ published.add(path);+ });+ await Promise.all([+ archiveProcessingInput("/downloads", new File(["first"], "a.pdf")),+ archiveProcessingInput("/downloads", new File(["later"], "a.pdf")),+ ]);+ expect(mocks.writeFile).toHaveBeenCalledOnce();+ expect(mocks.invoke).toHaveBeenCalledOnce();+});++test("failed publication removes staging without leaving an accepted backup", async () => {+ mocks.invoke.mockRejectedValueOnce(new Error("Publish failed"));+ await expect(+ archiveProcessingInput("/downloads", new File(["input"], "a.pdf")),+ ).rejects.toThrow("Publish failed");+ expect(mocks.remove).toHaveBeenCalledWith(mocks.writeFile.mock.calls[0][0]);+ expect(mocks.remove).not.toHaveBeenCalledWith("/downloads/.stirling/a.pdf");+});++test("unmounted folders cannot create backups", async () => {+ mocks.mounted.mockResolvedValue(false);+ await expect(+ archiveProcessingInput("/downloads", new File(["input"], "a.pdf")),+ ).rejects.toThrow("no longer mounted");+ expect(mocks.writeFile).not.toHaveBeenCalled();});test("failed staging leaves the input intact", async () => {@@ -70,3 +242,117 @@ test("Windows output paths match the directory listing's separator and casing",),).toBe(true);});++test("restoring a deleted input publishes complete bytes without replacing a returning file", async () => {+ mocks.diskState.mockResolvedValue({ availability: "gone" });+ await restoreProcessingFile(input.path, new File(["original"], input.name));+ expect(mocks.invoke).toHaveBeenCalledWith("publish_processing_file", {+ temporary: mocks.writeFile.mock.calls[0][0],+ path: input.path,+ });+ expect(mocks.writeFile).toHaveBeenCalledBefore(mocks.invoke);+ expect(mocks.rename).not.toHaveBeenCalled();+});++test("a returning input makes restore fail without consuming the original", async () => {+ mocks.diskState.mockResolvedValue({ availability: "gone" });+ mocks.invoke.mockRejectedValueOnce(new Error("File exists"));+ await expect(+ restoreProcessingFile(input.path, new File(["original"], input.name)),+ ).rejects.toThrow("File exists");+ expect(mocks.remove).toHaveBeenCalledWith(mocks.writeFile.mock.calls[0][0]);+ expect(mocks.remove).not.toHaveBeenCalledWith(input.path);+});++test.each(["permission", "offline", "unknown"])(+ "an unavailable input (%s) is never treated as deleted",+ async (reason) => {+ mocks.diskState.mockResolvedValue({ availability: "unavailable", reason });+ await expect(+ restoreProcessingFile(input.path, new File(["original"], input.name)),+ ).rejects.toThrow("Cannot access processing file");+ expect(mocks.writeFile).not.toHaveBeenCalled();+ },+);++test("restoring an edited input checks its current version", async () => {+ mocks.diskState.mockResolvedValue({+ availability: "present",+ size: 20,+ modifiedMs: 2000,+ });+ mocks.stat.mockResolvedValue({ size: 20, mtime: new Date(2000) });+ await restoreProcessingFile(input.path, new File(["original"], input.name));+ expect(mocks.rename).toHaveBeenCalledWith(expect.any(String), input.path);+ expect(mocks.invoke).not.toHaveBeenCalled();+});++test("an already deleted split output does not block a retry", async () => {+ mocks.diskState.mockResolvedValue({ availability: "gone" });+ mocks.remove.mockRejectedValue(new Error("File not found"));+ await expect(removeProcessingOutput(input)).resolves.toBeUndefined();+ expect(mocks.remove).not.toHaveBeenCalled();+});++test("an output that disappears during removal also counts as cleaned up", async () => {+ mocks.diskState+ .mockResolvedValueOnce({+ availability: "present",+ size: 10,+ modifiedMs: 1000,+ })+ .mockResolvedValue({ availability: "gone" });+ mocks.remove.mockRejectedValueOnce(new Error("File not found"));+ await expect(removeProcessingOutput(input)).resolves.toBeUndefined();+ expect(mocks.remove).toHaveBeenCalledWith(input.path);+});++test("split output permission errors remain retryable failures", async () => {+ mocks.remove.mockRejectedValueOnce(new Error("Permission denied"));+ await expect(removeProcessingOutput(input)).rejects.toThrow(+ "Permission denied",+ );+});++test("an edited split output is not deleted", async () => {+ mocks.diskState.mockResolvedValue({+ availability: "present",+ size: 11,+ modifiedMs: 2000,+ });+ await expect(removeProcessingOutput(input)).rejects.toThrow(+ "changed during processing",+ );+ expect(mocks.remove).not.toHaveBeenCalled();+});++test.each(["archive", "backup"])(+ "a linked %s is never accepted as an original",+ async (target) => {+ mocks.diskState.mockResolvedValue({+ availability: "present",+ size: 10,+ modifiedMs: 1000,+ });+ if (target === "backup")+ mocks.lstat.mockResolvedValueOnce({ isDirectory: true });+ mocks.lstat.mockResolvedValue({+ isDirectory: true,+ isFile: true,+ isSymlink: true,+ });+ await expect(+ archiveProcessingInput("/downloads", new File(["input"], "a.pdf")),+ ).rejects.toThrow();+ expect(mocks.writeFile).not.toHaveBeenCalled();+ },+);++test("restoring refuses an original replaced by a symbolic link", async () => {+ mocks.lstat+ .mockResolvedValueOnce({ isDirectory: true })+ .mockResolvedValueOnce({ isFile: true, isSymlink: true });+ await expect(+ readProcessingOriginal("/downloads/.stirling/a.pdf"),+ ).rejects.toThrow("not a regular archived file");+});diff --git a/frontend/editor/src/desktop/services/localProcessingDelivery.ts b/frontend/editor/src/desktop/services/localProcessingDelivery.tsindex 45364abb3a..784961f5d8 100644--- a/frontend/editor/src/desktop/services/localProcessingDelivery.ts+++ b/frontend/editor/src/desktop/services/localProcessingDelivery.ts@@ -1,7 +1,16 @@-import { mkdir, rename, remove, stat, writeFile } from "@tauri-apps/plugin-fs";+import {+ lstat,+ mkdir,+ rename,+ remove,+ stat,+ writeFile,+} from "@tauri-apps/plugin-fs";+import { invoke } from "@tauri-apps/api/core";+import { getDiskFileState } from "@app/services/desktopFileLink";import {readDiskFile,- writeDiskFile,+ isWithinMount,type DiskFileEntry,} from "@app/services/localFolderContents";import { generateId } from "@app/utils/generateId";@@ -40,29 +49,109 @@ export function sameProcessingFile();}-/** Refuses to overwrite a file edited while its server pipeline was running. */+/** Refuses edits made during processing; returns false only when absence is explicitly allowed. */export async function requireUnchangedProcessingFile(entry: DiskFileEntry,-): Promise<void> {- if (!sameProcessingFile(entry, await processingFileState(entry.path))) {+ allowMissing = false,+): Promise<boolean> {+ const current = allowMissing+ ? await existingProcessingFile(entry.path)+ : await processingFileState(entry.path);+ if (current && !sameProcessingFile(entry, current)) {throw new Error(`The file changed during processing: ${entry.name}`);}+ return current !== null;}-/** Keeps a recoverable original before any processed output replaces it. */+async function existingProcessingFile(+ path: string,+): Promise<DiskFileEntry | null> {+ const state = await getDiskFileState(path);+ if (state.availability === "gone") return null;+ if (state.availability === "unavailable") {+ throw new Error(`Cannot access processing file (${state.reason}): ${path}`);+ }+ return {+ path,+ name: path.split(/[/\\]/).pop()!,+ sizeBytes: state.size,+ lastModified: state.modifiedMs,+ };+}++/** Missing outputs are already cleaned up; inaccessible or edited outputs must survive restore. */+export async function removeProcessingOutput(+ entry: DiskFileEntry,+): Promise<void> {+ if (!(await requireUnchangedProcessingFile(entry, true))) return;+ try {+ await remove(entry.path);+ } catch (error) {+ if ((await getDiskFileState(entry.path)).availability !== "gone")+ throw error;+ }+}++/** Publishes the first complete original and preserves it through subsequent edits and runs. */export async function archiveProcessingInput(directory: string,file: File,): Promise<string> {- const archive = `${directory}/.stirling-originals`;+ const archive = processingPath(directory, ".stirling");+ const path = processingPath(archive, file.name);+ if (!(await isWithinMount(archive))) {+ throw new Error("The processing folder is no longer mounted");+ }await mkdir(archive, { recursive: true });- const name = await writeDiskFile(- archive,- `${generateId()}-${file.name}`,- file,+ const archiveInfo = await lstat(archive);+ if (!archiveInfo.isDirectory || archiveInfo.isSymlink)+ throw new Error("The original archive is not a directory");+ return navigator.locks.request(+ `processing-original:${directoryKey(path)}`,+ async () => {+ if (await existingProcessingFile(path)) {+ const info = await lstat(path);+ if (!info.isFile || info.isSymlink)+ throw new Error("The original is not a file");+ return path;+ }+ // Only a completed write is published as an original; crash leftovers stay hidden.+ const temporary = processingPath(+ archive,+ `.original-${generateId()}.tmp`,+ );+ try {+ await writeFile(temporary, new Uint8Array(await file.arrayBuffer()), {+ createNew: true,+ });+ await invoke("publish_processing_file", { temporary, path });+ return path;+ } finally {+ await remove(temporary).catch(() => {});+ }+ },);- if (!name) throw new Error("The processing folder is no longer mounted");- return processingPath(archive, name);+}++/** Restores a deleted input without overwriting a file that reappears during staging. */+export async function restoreProcessingFile(+ path: string,+ file: File,+): Promise<DiskFileEntry> {+ const current = await existingProcessingFile(path);+ if (current) return replaceProcessingFile(current, file);+ const temporary = `${path}.${generateId()}.tmp`;+ beginSelfWrite(path);+ try {+ await writeFile(temporary, new Uint8Array(await file.arrayBuffer()), {+ createNew: true,+ });+ await invoke("publish_processing_file", { temporary, path });+ return await processingFileState(path);+ } finally {+ await remove(temporary).catch(() => {});+ endSelfWrite(path);+ }}/** Stages bytes beside the input before replacing it; a failed write leaves the input intact. */@@ -88,6 +177,16 @@ export async function replaceProcessingFile(/** Reads an archived original through the same mounted-directory guard as other disk inputs. */export async function readProcessingOriginal(path: string): Promise<File> {+ const parent = path.replace(/[/\\][^/\\]+$/, "");+ const directory = await lstat(parent);+ const original = await lstat(path);+ if (+ !directory.isDirectory ||+ directory.isSymlink ||+ !original.isFile ||+ original.isSymlink+ )+ throw new Error("The original is not a regular archived file");const file = await readDiskFile(await processingFileState(path));if (!file) throw new Error("The processing folder is no longer mounted");return file;diff --git a/frontend/editor/src/desktop/services/localProcessingFolderStorage.ts b/frontend/editor/src/desktop/services/localProcessingFolderStorage.tsindex d713893e9e..458ccf1a43 100644--- a/frontend/editor/src/desktop/services/localProcessingFolderStorage.ts+++ b/frontend/editor/src/desktop/services/localProcessingFolderStorage.ts@@ -19,6 +19,10 @@ export interface LocalProcessingFile {/** Copies written by the desktop, used to recognise its own output and protect later edits. */outputs: DiskFileEntry[];originalPath?: string;+ /** Keeps backup ownership after restore while allowing the restored input to be processed again. */+ restored?: boolean;+ /** First confirmed absence, tied to the backup version so replacement restarts retention. */+ orphanedOriginal?: { since: number; version: string };}const DATABASE = {diff --git a/frontend/editor/src/desktop/services/localProcessingFolders.test.ts b/frontend/editor/src/desktop/services/localProcessingFolders.test.tsindex c84d0fd08a..d182305bcf 100644--- a/frontend/editor/src/desktop/services/localProcessingFolders.test.ts+++ b/frontend/editor/src/desktop/services/localProcessingFolders.test.ts@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({folders: new Map<string, LocalProcessingFolder>(),files: new Map<string, LocalProcessingFile>(),connected: true,+ diskContent: "input",mountedDirectories: ["/downloads"],otherDiskFiles: [] as DiskFileEntry[],disk: {@@ -22,9 +23,17 @@ const mocks = vi.hoisted(() => ({wait: vi.fn(),download: vi.fn(),replace: vi.fn(),+ restore: vi.fn(),+ removeOutput: vi.fn(),archive: vi.fn(),+ remove: vi.fn(),+ original: vi.fn(),+ reconcile: vi.fn(),}));-vi.mock("@tauri-apps/plugin-fs", () => ({ remove: vi.fn() }));+vi.mock("@app/services/localProcessingOriginals", () => ({+ reconcileLocalProcessingOriginals: mocks.reconcile,+}));+vi.mock("@tauri-apps/plugin-fs", () => ({ remove: mocks.remove }));vi.mock("@app/services/localFolderStorage", async (importOriginal) => ({...(await importOriginal<typeof import("@app/services/localFolderStorage")@@ -72,7 +81,7 @@ vi.mock("@app/services/localFolderContents", async (importOriginal) => ({directories: [],}),readDiskFile: async () =>- new File(["input"], "a.pdf", { type: "application/pdf" }),+ new File([mocks.diskContent], "a.pdf", { type: "application/pdf" }),writeDiskFile: vi.fn(),}));vi.mock("@app/services/serverPipeline", () => ({@@ -83,6 +92,8 @@ vi.mock("@app/services/serverPipeline", () => ({vi.mock("@app/services/localProcessingDelivery", () => ({archiveProcessingInput: mocks.archive,replaceProcessingFile: mocks.replace,+ restoreProcessingFile: mocks.restore,+ removeProcessingOutput: mocks.removeOutput,processingFileState: async () => mocks.disk,processingPath: (directory: string, name: string) => `${directory}/${name}`,sameProcessingFile: (a: DiskFileEntry, b: DiskFileEntry) =>@@ -93,12 +104,13 @@ vi.mock("@app/services/localProcessingDelivery", () => ({if (entry.lastModified !== mocks.disk.lastModified)throw new Error("File changed");},- readProcessingOriginal: vi.fn(),+ readProcessingOriginal: mocks.original,}));import {saveLocalProcessingFolder,sweepLocalProcessingFolder,scanLocalProcessingFolders,+ revertLocalProcessingFile,} from "@app/services/localProcessingFolders";const request = {@@ -112,9 +124,11 @@ function onlyFile() {describe("desktop processing folder handoff", () => {beforeEach(() => {vi.resetAllMocks();+ mocks.reconcile.mockImplementation(async (_folder, history) => history);mocks.files.clear();mocks.folders.clear();mocks.connected = true;+ mocks.diskContent = "input";mocks.mountedDirectories = ["/downloads"];mocks.otherDiskFiles = [];mocks.disk = {@@ -145,8 +159,13 @@ describe("desktop processing folder handoff", () => {mocks.download.mockResolvedValue(new File(["result"], "a.pdf", { type: "application/pdf" }),);- mocks.archive.mockResolvedValue(- "/downloads/.stirling-originals/original.pdf",+ mocks.archive.mockResolvedValue("/downloads/.stirling/a.pdf");+ mocks.original.mockResolvedValue(new File(["original"], "a.pdf"));+ mocks.restore.mockImplementation(async (_path, file) =>+ mocks.replace(mocks.disk, file),+ );+ mocks.removeOutput.mockImplementation(async (entry) =>+ mocks.remove(entry.path),);mocks.replace.mockImplementation(async () => {mocks.disk = { ...mocks.disk, lastModified: 2, sizeBytes: 5 };@@ -184,6 +203,85 @@ describe("desktop processing folder handoff", () => {expect(mocks.folders.size).toBe(0);});+ test("paused folders still reconcile backup retention without processing", async () => {+ const folder = await saveLocalProcessingFolder(request);+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));+ const paused = { ...folder, enabled: false };+ mocks.folders.set(folder.id, paused);+ mocks.reconcile.mockClear();++ await scanLocalProcessingFolders();++ expect(mocks.reconcile).toHaveBeenCalledWith(paused, [onlyFile()]);+ expect(mocks.submit).toHaveBeenCalledOnce();+ });++ test("editing and reprocessing a document still restores its uploaded original", async () => {+ mocks.archive.mockImplementation(async (_directory, file) => {+ mocks.original.mockResolvedValue(file);+ return "/downloads/.stirling/a.pdf";+ });+ const folder = await saveLocalProcessingFolder(request);+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));+ const originalPath = onlyFile().originalPath;+ mocks.disk = { ...mocks.disk, lastModified: 3 };+ mocks.diskContent = "annotated processed invoice";++ await sweepLocalProcessingFolder(folder.id);+ await waitFor(() => expect(mocks.submit).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(onlyFile().run.status).toBe("COMPLETED"));++ expect(onlyFile().originalPath).toBe(originalPath);+ expect(mocks.archive).toHaveBeenCalledOnce();+ await revertLocalProcessingFile(folder.id, "a.pdf");+ expect(mocks.replace).toHaveBeenLastCalledWith(+ expect.anything(),+ mocks.archive.mock.calls[0][1],+ );+ });++ test("an edited output can be restored before the next processing sweep", async () => {+ const folder = await saveLocalProcessingFolder(request);+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));+ mocks.disk = { ...mocks.disk, lastModified: 3 };+ const edited = { ...mocks.disk };++ await revertLocalProcessingFile(folder.id, "a.pdf");++ expect(mocks.replace).toHaveBeenLastCalledWith(edited, expect.any(File));+ expect(mocks.original).toHaveBeenCalledWith("/downloads/.stirling/a.pdf");+ expect(mocks.submit).toHaveBeenCalledOnce();+ });++ test.each([+ "/downloads/.stirling/a.pdf",+ "/downloads/.stirling-originals/old-a.pdf",+ ])(+ "restoring retains the backup at %s for later edits and restores",+ async (originalPath) => {+ mocks.archive.mockResolvedValueOnce(originalPath);+ const folder = await saveLocalProcessingFolder(request);+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));++ await revertLocalProcessingFile(folder.id, "a.pdf");++ expect(mocks.original).toHaveBeenCalledWith(originalPath);+ expect(mocks.remove).not.toHaveBeenCalledWith(originalPath);+ expect(onlyFile().originalPath).toBe(originalPath);+ expect(onlyFile().restored).toBe(true);++ await sweepLocalProcessingFolder(folder.id);+ await waitFor(() => expect(onlyFile().run.status).toBe("COMPLETED"));+ expect(mocks.submit).toHaveBeenCalledTimes(2);+ expect(mocks.archive).toHaveBeenCalledOnce();++ mocks.disk = { ...mocks.disk, lastModified: 4 };+ await revertLocalProcessingFile(folder.id, "a.pdf");+ expect(mocks.original).toHaveBeenLastCalledWith(originalPath);+ expect(mocks.remove).not.toHaveBeenCalledWith(originalPath);+ },+ );+test.each([["/downloads", "/downloads/invoices"],["/downloads/", "/downloads/invoices/2026"],@@ -284,6 +382,62 @@ describe("desktop processing folder handoff", () => {expect(onlyFile().run.error).toBe("File changed");});+ test("restoring a failed delivery restores the original even without recorded outputs", async () => {+ mocks.replace.mockRejectedValueOnce(new Error("Delivery failed"));+ const folder = await saveLocalProcessingFolder(request);+ await waitFor(() => expect(onlyFile()?.run.status).toBe("FAILED"));+ const entry = onlyFile();+ expect(entry.outputs).toEqual([]);++ await revertLocalProcessingFile(folder.id, "a.pdf");++ expect(mocks.replace).toHaveBeenLastCalledWith(+ entry.input,+ expect.any(File),+ );+ expect(mocks.remove).not.toHaveBeenCalledWith(entry.originalPath);+ expect(onlyFile().originalPath).toBe(entry.originalPath);+ expect(onlyFile().restored).toBe(true);+ });++ test("failed restoration retains the backup and processing record", async () => {+ const folder = await saveLocalProcessingFolder(request);+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));+ mocks.replace.mockRejectedValueOnce(new Error("Disk full"));++ await expect(revertLocalProcessingFile(folder.id, "a.pdf")).rejects.toThrow(+ "Disk full",+ );++ expect(mocks.remove).not.toHaveBeenCalled();+ expect(mocks.files.size).toBe(1);+ });++ test("a partially removed split output set can be restored again", async () => {+ const folder = await saveLocalProcessingFolder(request);+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));+ const outputs = ["part-1.pdf", "part-2.pdf"].map((name) => ({+ ...mocks.disk,+ name,+ path: `/downloads/${name}`,+ }));+ onlyFile().outputs = outputs;+ mocks.removeOutput+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("Permission denied"));++ await expect(revertLocalProcessingFile(folder.id, "a.pdf")).rejects.toThrow(+ "Permission denied",+ );+ expect(onlyFile().outputs).toEqual(outputs);+ expect(onlyFile().restored).not.toBe(true);++ await revertLocalProcessingFile(folder.id, "a.pdf");+ expect(onlyFile().outputs).toEqual([]);+ expect(onlyFile().restored).toBe(true);+ expect(onlyFile().originalPath).toBe("/downloads/.stirling/a.pdf");+ });+test("reconnect resumes an existing server run without charging another submission", async () => {mocks.wait.mockImplementationOnce(async () => {mocks.connected = false;diff --git a/frontend/editor/src/desktop/services/localProcessingFolders.ts b/frontend/editor/src/desktop/services/localProcessingFolders.tsindex a34df334ed..c4f8eb19eb 100644--- a/frontend/editor/src/desktop/services/localProcessingFolders.ts+++ b/frontend/editor/src/desktop/services/localProcessingFolders.ts@@ -1,4 +1,3 @@-import { remove } from "@tauri-apps/plugin-fs";import { directoryKey } from "@app/services/localFolderStorage";import {isWithinMount,@@ -27,6 +26,8 @@ import {processingPath,readProcessingOriginal,replaceProcessingFile,+ restoreProcessingFile,+ removeProcessingOutput,requireUnchangedProcessingFile,sameProcessingFile,} from "@app/services/localProcessingDelivery";@@ -37,6 +38,7 @@ import type {} from "@app/services/processingFolderApi";import type { BackendPipelineStep } from "@app/services/policyPipeline";import { generateId } from "@app/utils/generateId";+import { reconcileLocalProcessingOriginals } from "@app/services/localProcessingOriginals";const running = new Map<string, Promise<void>>();const cancelled = new Set<string>();@@ -290,7 +292,10 @@ async function queueLocalProcessingFiles(): Promise<SweepOutcome> {const folder = await requireLocalProcessingFolder(id);const listing = await listDirectory(folder.directory);- const history = await storage.files(id);+ const history = await reconcileLocalProcessingOriginals(+ folder,+ await storage.files(id),+ );const outputs = history.flatMap((entry) => entry.outputs);const result: SweepOutcome = {runIds: [],@@ -313,6 +318,7 @@ async function queueLocalProcessingFiles(if (output ||(previous?.run.status === "COMPLETED" &&+ !previous.restored &&sameProcessingFile(previous.input, input))) {result.alreadyProcessed++;@@ -332,10 +338,7 @@ async function queueLocalProcessingFiles(folderId: id,input,outputs: previous?.outputs ?? [],- originalPath:- previous && sameProcessingFile(previous.input, input)- ? previous.originalPath- : undefined,+ originalPath: previous?.originalPath,run: {runId: `queued:${generateId()}`,status: "PENDING",@@ -379,41 +382,59 @@ export async function deleteLocalProcessingFolder(id: string): Promise<void> {cancelled.delete(id);}-/** Restores one archived input only if none of this run's outputs were subsequently edited. */+/** Restores the original over the current input; edited split outputs are never silently deleted. */export async function revertLocalProcessingFile(id: string,name: string,): Promise<void> {- const folder = await requireLocalProcessingFolder(id);- await storage.saveFolder({ ...folder, enabled: false });- const entry = (await storage.files(id)).find(- (file) => file.input.name === name,- );- if (- !entry?.originalPath ||- !TERMINAL.has(entry.run.status) ||- running.has(id)- ) {- throw new Error("Wait for processing to finish before restoring this file");- }- for (const output of entry.outputs)- await requireUnchangedProcessingFile(output);- const replacement = entry.outputs.find(- (output) => output.path === entry.input.path,+ return navigator.locks.request(+ `processing:${id}`,+ { ifAvailable: true },+ async (lock) => {+ if (!lock)+ throw new Error(+ "Wait for processing to finish before restoring this file",+ );+ const folder = await requireLocalProcessingFolder(id);+ await storage.saveFolder({ ...folder, enabled: false });+ const entry = (await storage.files(id)).find(+ (file) => file.input.name === name,+ );+ if (+ !entry?.originalPath ||+ !TERMINAL.has(entry.run.status) ||+ running.has(id)+ ) {+ throw new Error(+ "Wait for processing to finish before restoring this file",+ );+ }+ for (const output of entry.outputs) {+ if (directoryKey(output.path) !== directoryKey(entry.input.path))+ await requireUnchangedProcessingFile(output, true);+ }+ const restored = await restoreProcessingFile(+ entry.input.path,+ await readProcessingOriginal(entry.originalPath),+ );+ for (const output of entry.outputs) {+ if (directoryKey(output.path) !== directoryKey(entry.input.path))+ await removeProcessingOutput(output);+ }+ await storage.saveFile({+ ...entry,+ input: restored,+ outputs: [],+ restored: true,+ serverRunId: undefined,+ orphanedOriginal: undefined,+ run: { status: "COMPLETED" },+ });+ },);- if (replacement) {- await replaceProcessingFile(- replacement,- await readProcessingOriginal(entry.originalPath),- );- }- for (const output of entry.outputs) {- if (output.path !== entry.input.path) await remove(output.path);- }- await storage.deleteFile(entry.id);}-/** Scans enabled desktop folders while signed in. Each folder keeps at most one active upload. */+/** Scans while signed in; paused folders still expire orphaned originals under the processing lock. */export async function scanLocalProcessingFolders(): Promise<void> {for (const folder of await localProcessingFolders()) {if (folder.enabled && !running.has(folder.id)) {@@ -426,6 +447,21 @@ export async function scanLocalProcessingFolders(): Promise<void> {)) {startDrain(folder.id, false);+ } else if (!running.has(folder.id)) {+ await navigator.locks+ .request(+ `processing:${folder.id}`,+ { ifAvailable: true },+ async (lock) => {+ if (!lock) return;+ const current = await requireLocalProcessingFolder(folder.id);+ await reconcileLocalProcessingOriginals(+ current,+ await storage.files(folder.id),+ );+ },+ )+ .catch(() => {});}}}diff --git a/frontend/editor/src/desktop/services/localProcessingOriginals.test.ts b/frontend/editor/src/desktop/services/localProcessingOriginals.test.tsnew file mode 100644index 0000000000..a53e5e63cd--- /dev/null+++ b/frontend/editor/src/desktop/services/localProcessingOriginals.test.ts@@ -0,0 +1,269 @@+import { beforeEach, expect, test, vi } from "vitest";+import type {+ LocalProcessingFile,+ LocalProcessingFolder,+} from "@app/services/localProcessingFolderStorage";++const mocks = vi.hoisted(() => ({+ exists: vi.fn(),+ lstat: vi.fn(),+ readDir: vi.fn(),+ remove: vi.fn(),+ mounted: vi.fn(),+ session: vi.fn(),+ save: vi.fn(),+ delete: vi.fn(),+ files: new Map<string, LocalProcessingFile>(),+ present: new Set<string>(),+}));+vi.mock("@tauri-apps/plugin-fs", () => mocks);+vi.mock("@app/services/localFolderContents", () => ({+ isWithinMount: mocks.mounted,+}));+vi.mock("@app/services/serverAutomationSession", () => ({+ requireAutomationSession: mocks.session,+}));+vi.mock("@app/services/localProcessingFolderStorage", () => ({+ localProcessingFolderStorage: {+ saveFile: mocks.save,+ deleteFile: mocks.delete,+ },+}));+vi.mock("@app/services/localProcessingDelivery", () => ({+ processingPath: (directory: string, name: string) => `${directory}/${name}`,+}));+import { reconcileLocalProcessingOriginals } from "@app/services/localProcessingOriginals";++const DAY = 24 * 60 * 60 * 1000;+const START = Date.UTC(2026, 8, 1);+const folder: LocalProcessingFolder = {+ id: "desktop:folder",+ sessionKey: "owner",+ directory: "/downloads",+ enabled: false,+ folderId: null,+ name: "Downloads",+ steps: [],+ output: {},+};+const input = {+ path: "/downloads/a.pdf",+ name: "a.pdf",+ sizeBytes: 10,+ lastModified: 1,+};+const original = {+ isFile: true,+ isSymlink: false,+ size: 10,+ mtime: new Date(1),+ birthtime: new Date(1),+};++function entry(): LocalProcessingFile {+ return mocks.files.get("file")!;+}++function scan(now: number) {+ return reconcileLocalProcessingOriginals(+ folder,+ [...mocks.files.values()],+ now,+ );+}++beforeEach(() => {+ vi.resetAllMocks();+ mocks.files.clear();+ mocks.present.clear();+ mocks.files.set("file", {+ id: "file",+ folderId: folder.id,+ input,+ outputs: [input],+ originalPath: "/downloads/.stirling/a.pdf",+ run: { status: "COMPLETED" },+ });+ mocks.readDir.mockImplementation(async (path) =>+ path === folder.directory+ ? []+ : [{ name: entry().originalPath!.split(/[/\\]/).pop()! }],+ );+ mocks.exists.mockImplementation(+ async (path) => path.includes("/.stirling") || mocks.present.has(path),+ );+ mocks.lstat.mockImplementation(async (path) =>+ path.endsWith(".pdf") ? original : { isDirectory: true },+ );+ mocks.mounted.mockResolvedValue(true);+ mocks.save.mockImplementation(async (file) => {+ mocks.files.set(file.id, file);+ });+ mocks.delete.mockImplementation(async (id) => {+ mocks.files.delete(id);+ });+});++test.each([+ "/downloads/.stirling/a.pdf",+ "/downloads/.stirling-originals/old-a.pdf",+])(+ "expires %s seven days after first absence using persisted state",+ async (originalPath) => {+ entry().originalPath = originalPath;+ await scan(START);+ expect(entry().orphanedOriginal?.since).toBe(START);+ await scan(START + 7 * DAY - 1);+ expect(mocks.remove).not.toHaveBeenCalled();+ mocks.files.set("file", structuredClone(entry()));++ await scan(START + 7 * DAY);++ expect(mocks.remove).toHaveBeenCalledWith(originalPath);+ expect(mocks.files.size).toBe(0);+ },+);++test("a returned file resets the grace period", async () => {+ await scan(START);+ mocks.readDir.mockResolvedValueOnce([{ name: "a.pdf" }]);+ await scan(START + 6 * DAY);+ expect(entry().orphanedOriginal).toBeUndefined();+ await scan(START + 8 * DAY);+ await scan(START + 14 * DAY);+ expect(mocks.remove).not.toHaveBeenCalled();+ await scan(START + 15 * DAY);+ expect(mocks.remove).toHaveBeenCalledOnce();+});++test("unreadable files in the raw listing still keep their originals", async () => {+ mocks.readDir.mockResolvedValue([{ name: "a.pdf", isFile: true }]);+ mocks.lstat.mockRejectedValue(new Error("Permission denied"));+ await scan(START);+ await scan(START + 100 * DAY);+ expect(mocks.lstat).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(entry().orphanedOriginal).toBeUndefined();+});++test("failed directory listings cannot authorize deletion", async () => {+ await scan(START);+ mocks.readDir.mockRejectedValue(new Error("Drive unavailable"));+ await expect(scan(START + 8 * DAY)).rejects.toThrow("Drive unavailable");+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(entry().orphanedOriginal?.since).toBe(START);+});++test("in-flight work keeps its backup and clears expiry", async () => {+ await scan(START);+ entry().run.status = "RUNNING";+ await scan(START + 8 * DAY);+ expect(entry().orphanedOriginal).toBeUndefined();+ expect(mocks.remove).not.toHaveBeenCalled();+});++test("any remaining split output keeps the original", async () => {+ entry().outputs = [+ { ...input, name: "part1.pdf", path: "/downloads/part1.pdf" },+ ];+ mocks.readDir.mockResolvedValue([{ name: "part1.pdf" }]);+ await scan(START);+ await scan(START + 100 * DAY);+ expect(entry().orphanedOriginal).toBeUndefined();+ expect(mocks.remove).not.toHaveBeenCalled();+});++test("a file that returns after listing is rechecked before deletion", async () => {+ await scan(START);+ let checks = 0;+ mocks.exists.mockImplementation(async (path) => {+ if (path.includes("/.stirling")) return true;+ return ++checks > 1;+ });+ await scan(START + 8 * DAY);+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(entry().orphanedOriginal).toBeUndefined();+});++test("changed backup contents receive a new grace period", async () => {+ await scan(START);+ mocks.lstat.mockImplementation(async (path) =>+ path.endsWith(".pdf") ? { ...original, size: 20 } : { isDirectory: true },+ );+ await scan(START + 8 * DAY);+ expect(entry().orphanedOriginal?.since).toBe(START + 8 * DAY);+ expect(mocks.remove).not.toHaveBeenCalled();+});++test("failed deletes retain their record and are retried", async () => {+ await scan(START);+ mocks.remove.mockRejectedValueOnce(new Error("File locked"));+ await scan(START + 8 * DAY);+ expect(mocks.files.size).toBe(1);+ expect(mocks.delete).not.toHaveBeenCalled();+ await scan(START + 8 * DAY + 1);+ expect(mocks.remove).toHaveBeenCalledTimes(2);+ expect(mocks.files.size).toBe(0);+});++test("unmounting before expiry prevents removal", async () => {+ await scan(START);+ mocks.mounted.mockResolvedValue(false);+ await scan(START + 8 * DAY);+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(mocks.files.size).toBe(1);+});++test("signing out before expiry prevents removal", async () => {+ await scan(START);+ mocks.session.mockRejectedValue(new Error("Signed out"));+ await scan(START + 8 * DAY);+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(mocks.files.size).toBe(1);+});++test("paths outside the two managed archive directories cannot be removed", async () => {+ entry().originalPath = "/downloads/important.pdf";+ await scan(START);+ await scan(START + 100 * DAY);+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(entry().orphanedOriginal).toBeUndefined();+});++test("symlinked archive directories are not followed for cleanup", async () => {+ mocks.lstat.mockResolvedValue({ isDirectory: true, isSymlink: true });+ await scan(START);+ await scan(START + 100 * DAY);+ expect(mocks.remove).not.toHaveBeenCalled();+});++test("a backup already deleted on disk releases its stale history", async () => {+ mocks.readDir.mockResolvedValue([]);+ mocks.exists.mockResolvedValue(false);+ await scan(START);+ expect(mocks.remove).not.toHaveBeenCalled();+ expect(mocks.files.size).toBe(0);+});++test("unreadable backup metadata retains its history when exists returns false", async () => {+ mocks.exists.mockResolvedValue(false);+ mocks.lstat.mockImplementation(async (path) => {+ if (path.endsWith(".pdf")) throw new Error("Permission denied");+ return { isDirectory: true };+ });++ expect(await scan(START)).toEqual([entry()]);+ expect(mocks.delete).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalled();+});++test("an unreadable archive listing retains its backup history", async () => {+ mocks.readDir.mockImplementation(async (path) => {+ if (path !== folder.directory) throw new Error("Permission denied");+ return [];+ });++ expect(await scan(START)).toEqual([entry()]);+ expect(mocks.delete).not.toHaveBeenCalled();+ expect(mocks.remove).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/desktop/services/localProcessingOriginals.ts b/frontend/editor/src/desktop/services/localProcessingOriginals.tsnew file mode 100644index 0000000000..cc8dea3d1d--- /dev/null+++ b/frontend/editor/src/desktop/services/localProcessingOriginals.ts@@ -0,0 +1,140 @@+import {+ exists,+ lstat,+ readDir,+ remove,+ type FileInfo,+} from "@tauri-apps/plugin-fs";+import { directoryKey } from "@app/services/localFolderStorage";+import { isWithinMount } from "@app/services/localFolderContents";+import { processingPath } from "@app/services/localProcessingDelivery";+import {+ localProcessingFolderStorage as storage,+ type LocalProcessingFile,+ type LocalProcessingFolder,+} from "@app/services/localProcessingFolderStorage";+import { requireAutomationSession } from "@app/services/serverAutomationSession";++const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;+const TERMINAL = new Set(["COMPLETED", "FAILED", "CANCELLED"]);++function backupVersion(info: FileInfo): string {+ return `${info.size}:${info.mtime?.getTime() ?? 0}:${info.birthtime?.getTime() ?? 0}`;+}++async function anyPresent(paths: string[]): Promise<boolean> {+ for (const path of paths) if (await exists(path)) return true;+ return false;+}++async function clearExpiry(+ entry: LocalProcessingFile,+): Promise<LocalProcessingFile> {+ if (!entry.orphanedOriginal) return entry;+ const updated = { ...entry, orphanedOriginal: undefined };+ await storage.saveFile(updated);+ return updated;+}++async function reconcileOriginal(+ folder: LocalProcessingFolder,+ entry: LocalProcessingFile,+ present: Set<string>,+ now: number,+): Promise<LocalProcessingFile | null> {+ if (!entry.originalPath || !TERMINAL.has(entry.run.status))+ return clearExpiry(entry);+ const paths = [+ ...new Set(+ [entry.input, ...entry.outputs].map((file) =>+ processingPath(folder.directory, file.name),+ ),+ ),+ ];+ if (+ paths.some((path) => present.has(directoryKey(path))) ||+ (await anyPresent(paths))+ ) {+ return clearExpiry(entry);+ }+ const name = entry.originalPath.split(/[/\\]/).pop()!;+ const archive = [".stirling", ".stirling-originals"]+ .map((directory) => processingPath(folder.directory, directory))+ .find(+ (directory) =>+ directoryKey(processingPath(directory, name)) ===+ directoryKey(entry.originalPath!),+ );+ if (!archive) return entry;+ const archiveInfo = await lstat(archive);+ if (!archiveInfo.isDirectory || archiveInfo.isSymlink) return entry;+ const originalKey = directoryKey(entry.originalPath);+ const archived = await readDir(archive);+ if (+ !archived.some(+ (file) =>+ directoryKey(processingPath(archive, file.name)) === originalKey,+ )+ ) {+ await storage.deleteFile(entry.id);+ return null;+ }+ const info = await lstat(entry.originalPath);+ if (!info.isFile || info.isSymlink) return entry;+ const version = backupVersion(info);+ const orphaned = entry.orphanedOriginal;+ if (+ !orphaned ||+ orphaned.version !== version ||+ !Number.isFinite(orphaned.since) ||+ orphaned.since < 0 ||+ orphaned.since > now+ ) {+ const updated = { ...entry, orphanedOriginal: { since: now, version } };+ await storage.saveFile(updated);+ return updated;+ }+ if (now - orphaned.since < RETENTION_MS) return entry;+ await requireAutomationSession(folder.sessionKey);+ if (!(await isWithinMount(folder.directory))) return entry;+ if (await anyPresent(paths)) return clearExpiry(entry);+ const current = await lstat(entry.originalPath);+ if (+ !current.isFile ||+ current.isSymlink ||+ backupVersion(current) !== version+ )+ return entry;+ await remove(entry.originalPath);+ await storage.deleteFile(entry.id);+ return null;+}++/**+ * Reclaims backups after seven days without an input or output. The caller holds the folder's+ * processing lock and validates its session/mount. Raw directory entries keep unreadable files+ * present: the UI listing omits files whose stat fails and cannot establish deletion.+ */+export async function reconcileLocalProcessingOriginals(+ folder: LocalProcessingFolder,+ history: LocalProcessingFile[],+ now = Date.now(),+): Promise<LocalProcessingFile[]> {+ const entries = await readDir(folder.directory);+ const present = new Set(+ entries.map((entry) =>+ directoryKey(processingPath(folder.directory, entry.name)),+ ),+ );+ const retained: LocalProcessingFile[] = [];+ for (const entry of history) {+ try {+ const updated = await reconcileOriginal(folder, entry, present, now);+ if (updated) retained.push(updated);+ } catch {+ // Unreadable backups and failed deletions are retried on the next successful scan.+ retained.push(entry);+ }+ }+ return retained;+}diff --git a/frontend/editor/src/desktop/services/processingFolderApi.ts b/frontend/editor/src/desktop/services/processingFolderApi.tsindex 267b0d6e23..8864d0115a 100644--- a/frontend/editor/src/desktop/services/processingFolderApi.ts+++ b/frontend/editor/src/desktop/services/processingFolderApi.ts@@ -78,7 +78,9 @@ export async function fetchProcessingFolderRuns(): Promise<server.ProcessingFolderRun[]> {if (!isLocalProcessingFolder(id)) return server.fetchProcessingFolderRuns(id);await requireLocalProcessingFolder(id);- return (await storage.files(id)).map((entry) => entry.run);+ return (await storage.files(id))+ .filter((entry) => !entry.restored)+ .map((entry) => entry.run);}export async function fetchMountedFiles(@@ -94,7 +96,7 @@ export async function fetchMountedFiles(record.input.name === file.name ||record.outputs.some((output) => output.name === file.name),);- const status = entry?.run.status;+ const status = entry?.restored ? undefined : entry?.run.status;return {name: file.name,sizeBytes: file.sizeBytes,