#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
fix(jpdfium): stop the backend gracefully and reclaim extraction dirs (#8202)
briosd68870dc2cd7
diff --git a/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.java b/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.javaindex 438481c212..0df3b2bc72 100644--- a/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.java+++ b/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.java@@ -1,9 +1,18 @@package stirling.software.common.service;import java.io.IOException;+import java.io.UncheckedIOException;+import java.nio.channels.FileChannel;+import java.nio.channels.FileLock;import java.nio.file.Files;+import java.nio.file.InvalidPathException;+import java.nio.file.LinkOption;import java.nio.file.Path;+import java.nio.file.StandardOpenOption;+import java.util.ArrayList;import java.util.Arrays;+import java.util.List;+import java.util.Locale;import java.util.Set;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;@@ -47,6 +56,17 @@ public class TempFileCleanupService {// Maximum recursion depth for directory traversalprivate static final int MAX_RECURSION_DEPTH = 5;+ // A JPDFium dir younger than this may belong to a JVM that is still starting+ private static final long JPDFIUM_DIR_GRACE_MILLIS = 60 * 60 * 1000;++ // Names of the jpdfium bridge library across platforms; every extraction dir holds one+ private static final Set<String> JPDFIUM_BRIDGE_FILES =+ Set.of("jpdfium.dll", "libjpdfium.dylib", "libjpdfium.so");++ // Held by the owning JVM for its lifetime in fallback extraction dirs+ private static final String JPDFIUM_LOCK_FILE = ".lock";+ private static final String JPDFIUM_DIR_PREFIX = "jpdfium-";+// File patterns that identify our temp filesprivate static final Predicate<String> IS_OUR_TEMP_FILE =fileName ->@@ -190,11 +210,122 @@ public class TempFileCleanupService {long maxAgeMillis = containerMode ? 0 : 24 * 60 * 60 * 1000; // 0 or 24 hoursint totalDeletedCount = cleanupUnregisteredFiles(containerMode, false, maxAgeMillis);+ totalDeletedCount += cleanupStaleJpdfiumDirs();log.info("Startup cleanup complete. Deleted {} temporary files/directories",totalDeletedCount);}+ /**+ * Removes JPDFium extraction dirs leaked by older versions on Windows. The age gate keeps a dir+ * whose JVM may still be extracting, the content check keeps the sweep away from a same-named+ * dir this application did not create, and the lock check keeps a running JVM's fallback dir:+ * JPDFium holds {@code .lock} there for its lifetime.+ *+ * @return number of directories removed+ */+ private int cleanupStaleJpdfiumDirs() {+ int deletedCount = 0;+ for (Path root : jpdfiumScanRoots()) {+ if (!Files.isDirectory(root)) continue;+ List<Path> stale;+ try (Stream<Path> entries = Files.list(root)) {+ stale =+ entries.filter(p -> Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS))+ .filter(+ p ->+ p.getFileName()+ .toString()+ .startsWith(JPDFIUM_DIR_PREFIX))+ .filter(p -> isOlderThan(p, JPDFIUM_DIR_GRACE_MILLIS))+ .filter(TempFileCleanupService::looksLikeJpdfiumExtraction)+ .filter(dir -> !isJpdfiumDirInUse(dir))+ .toList();+ } catch (IOException | UncheckedIOException e) {+ log.debug("JPDFium temp scan failed for {}: {}", root, e.getMessage());+ continue;+ }+ for (Path dir : stale) {+ try {+ GeneralUtils.deleteDirectory(dir);+ deletedCount++;+ log.info("Removed stale JPDFium extraction dir: {}", dir);+ } catch (IOException e) {+ // Windows keeps loaded DLLs locked; a later startup retries.+ log.debug("Could not remove JPDFium dir {}: {}", dir, e.getMessage());+ }+ }+ }+ return deletedCount;+ }++ /**+ * JPDFium extracts into {@code java.io.tmpdir}; the configured system and base temp dirs+ * receive the dirs only when the JVM temp dir points at them, so all three are scanned and+ * deduplicated. An unusable configured path is skipped instead of aborting startup.+ */+ private Path[] jpdfiumScanRoots() {+ List<Path> roots = new ArrayList<>(3);+ addJpdfiumScanRoot(roots, System.getProperty("java.io.tmpdir"));+ ApplicationProperties.TempFileManagement tempFiles =+ applicationProperties.getSystem().getTempFileManagement();+ addJpdfiumScanRoot(roots, tempFiles.getSystemTempDir());+ addJpdfiumScanRoot(roots, tempFiles.getBaseTmpDir());+ return roots.toArray(Path[]::new);+ }++ private static void addJpdfiumScanRoot(List<Path> roots, String rawPath) {+ if (rawPath == null || rawPath.isBlank()) return;+ try {+ Path root = Path.of(rawPath);+ if (!roots.contains(root)) {+ roots.add(root);+ }+ } catch (InvalidPathException e) {+ log.debug("Skipping invalid temp scan root '{}': {}", rawPath, e.getMessage());+ }+ }++ /**+ * Every extraction dir holds the jpdfium bridge next to pdfium itself; requiring that exact+ * artifact keeps the sweep from deleting an unrelated dir that happens to share the prefix.+ */+ private static boolean looksLikeJpdfiumExtraction(Path dir) {+ try (Stream<Path> entries = Files.list(dir)) {+ return entries.map(path -> path.getFileName().toString().toLowerCase(Locale.ROOT))+ .anyMatch(JPDFIUM_BRIDGE_FILES::contains);+ } catch (IOException | UncheckedIOException e) {+ return false;+ }+ }++ /**+ * A fallback extraction dir holds a {@code .lock} the owning JVM keeps locked for its whole+ * lifetime; a free or absent lock means the dir is a leftover. Anything unreadable counts as in+ * use so cleanup fails closed.+ */+ private static boolean isJpdfiumDirInUse(Path dir) {+ Path lockFile = dir.resolve(JPDFIUM_LOCK_FILE);+ if (!Files.exists(lockFile, LinkOption.NOFOLLOW_LINKS)) return false;+ try (FileChannel channel =+ FileChannel.open(+ lockFile, StandardOpenOption.READ, StandardOpenOption.WRITE);+ FileLock lock = channel.tryLock()) {+ return lock == null;+ } catch (IOException | RuntimeException e) {+ return true;+ }+ }++ private static boolean isOlderThan(Path path, long ageMillis) {+ try {+ return System.currentTimeMillis() - Files.getLastModifiedTime(path).toMillis()+ > ageMillis;+ } catch (IOException e) {+ return false;+ }+ }+/*** Clean up unregistered temporary files across all configured temp directories.*@@ -346,6 +477,11 @@ public class TempFileCleanupService {}if (Files.isDirectory(path)) {+ if (fileName.startsWith(JPDFIUM_DIR_PREFIX)) {+ // The lock-aware sweep owns these; unlinking a+ // live .lock would hide it from that sweep.+ return;+ }subdirectories.add(path);return;}diff --git a/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.java b/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.javaindex cfbe950574..eb9516c7df 100644--- a/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.java+++ b/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.java@@ -9,11 +9,15 @@ import static org.mockito.Mockito.when;import java.io.File;import java.io.IOException;+import java.nio.channels.FileChannel;+import java.nio.channels.FileLock;import java.nio.file.Files;import java.nio.file.Path;+import java.nio.file.StandardOpenOption;import java.nio.file.attribute.FileTime;import java.util.HashSet;import java.util.Set;+import java.util.concurrent.atomic.AtomicInteger;import java.util.function.Consumer;import org.junit.jupiter.api.AfterEach;@@ -85,6 +89,23 @@ class TempFileCleanupServiceMoreTest {file, FileTime.fromMillis(System.currentTimeMillis() - millisAgo));}+ /**+ * Points java.io.tmpdir at a throwaway root so the sweep under test never touches the+ * machine's.+ */+ private void withJvmTmpDir(Path root, Runnable action) {+ String oldTmp = System.getProperty("java.io.tmpdir");+ try {+ Files.createDirectories(root);+ System.setProperty("java.io.tmpdir", root.toString());+ action.run();+ } catch (IOException e) {+ throw new RuntimeException(e);+ } finally {+ System.setProperty("java.io.tmpdir", oldTmp);+ }+ }+@Nested@DisplayName("isContainerMode")class ContainerMode {@@ -165,10 +186,173 @@ class TempFileCleanupServiceMoreTest {Path stale = Files.createFile(customTempDir.resolve("stirling-pdf-stale.tmp"));backdate(stale, 48L * 60 * 60 * 1000); // 48h old, beyond non-container 24h cutoff- cleanupService.init();+ withJvmTmpDir(tempDir.resolve("jvm-tmp-cleanup"), cleanupService::init);++ assertThat(Files.exists(stale)).isFalse();+ }+ }++ @Nested+ @DisplayName("cleanupStaleJpdfiumDirs")+ class JpdfiumDirs {++ @Test+ @DisplayName("removes stale extraction dirs and keeps fresh ones at startup")+ void removesStaleJpdfiumDirs() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);++ Path stale = Files.createDirectories(systemTempDir.resolve("jpdfium-old"));+ Files.writeString(stale.resolve("jpdfium.dll"), "dll");+ backdate(stale, 2L * 60 * 60 * 1000);+ Path fresh = Files.createDirectories(systemTempDir.resolve("jpdfium-fresh"));++ withJvmTmpDir(tempDir.resolve("jvm-tmp-a"), cleanupService::init);++ assertThat(Files.exists(stale)).isFalse();+ assertThat(Files.exists(fresh)).isTrue();+ }++ @Test+ @DisplayName("also scans the configured base temp dir")+ void scansBaseTempDir() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);++ Path stale = Files.createDirectories(customTempDir.resolve("jpdfium-old"));+ Files.writeString(stale.resolve("jpdfium.dll"), "dll");+ backdate(stale, 2L * 60 * 60 * 1000);++ withJvmTmpDir(tempDir.resolve("jvm-tmp-b"), cleanupService::init);++ assertThat(Files.exists(stale)).isFalse();+ }++ @Test+ @DisplayName("scans the JVM temp dir even when the configured system temp dir differs")+ void scansJvmTempDir() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);++ Path jvmTmp = tempDir.resolve("jvm-tmp");+ Path stale = Files.createDirectories(jvmTmp.resolve("jpdfium-old"));+ Files.writeString(stale.resolve("jpdfium.dll"), "dll");+ backdate(stale, 2L * 60 * 60 * 1000);++ withJvmTmpDir(jvmTmp, cleanupService::init);++ assertThat(Files.exists(stale)).isFalse();+ }++ @Test+ @DisplayName("keeps a prefixed dir whose content is not a JPDFium extraction")+ void keepsUnrelatedContent() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);++ Path impostor = Files.createDirectories(systemTempDir.resolve("jpdfium-notours"));+ Files.writeString(impostor.resolve("jpdfium-notes.txt"), "unrelated");+ backdate(impostor, 2L * 60 * 60 * 1000);++ withJvmTmpDir(tempDir.resolve("jvm-tmp-c"), cleanupService::init);++ assertThat(Files.exists(impostor)).isTrue();+ }++ @Test+ @DisplayName("recognizes the bridge artifact name of every platform")+ void recognizesBridgeNames() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);++ Path linux = Files.createDirectories(systemTempDir.resolve("jpdfium-linux"));+ Files.writeString(linux.resolve("libjpdfium.so"), "so");+ Path mac = Files.createDirectories(systemTempDir.resolve("jpdfium-mac"));+ Files.writeString(mac.resolve("libjpdfium.dylib"), "dylib");+ Path win = Files.createDirectories(systemTempDir.resolve("jpdfium-win"));+ Files.writeString(win.resolve("jpdfium.dll"), "dll");+ for (Path dir : new Path[] {linux, mac, win}) {+ backdate(dir, 2L * 60 * 60 * 1000);+ }++ withJvmTmpDir(tempDir.resolve("jvm-tmp-f"), cleanupService::init);++ assertThat(Files.exists(linux)).isFalse();+ assertThat(Files.exists(mac)).isFalse();+ assertThat(Files.exists(win)).isFalse();+ }++ @Test+ @DisplayName("skips an invalid configured root without aborting startup")+ void skipsInvalidConfiguredRoot() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);+ when(tempFileManagement.getSystemTempDir()).thenReturn("bad\u0000root");++ Path stale = Files.createDirectories(customTempDir.resolve("jpdfium-old"));+ Files.writeString(stale.resolve("jpdfium.dll"), "dll");+ backdate(stale, 2L * 60 * 60 * 1000);++ withJvmTmpDir(tempDir.resolve("jvm-tmp-d"), cleanupService::init);assertThat(Files.exists(stale)).isFalse();}++ @Test+ @DisplayName("keeps an extraction dir whose lock is held by a running JVM")+ void keepsLockedExtractionDir() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);++ Path live = Files.createDirectories(systemTempDir.resolve("jpdfium-live"));+ Files.writeString(live.resolve("jpdfium.dll"), "dll");+ Path lockFile = live.resolve(".lock");+ Files.writeString(lockFile, "");+ backdate(live, 2L * 60 * 60 * 1000);++ try (FileChannel channel =+ FileChannel.open(+ lockFile, StandardOpenOption.READ, StandardOpenOption.WRITE);+ FileLock lock = channel.lock()) {+ withJvmTmpDir(tempDir.resolve("jvm-tmp-g"), cleanupService::init);+ assertThat(Files.exists(live)).isTrue();+ }+ }++ @Test+ @DisplayName("removes an extraction dir whose lock is free")+ void removesUnlockedExtractionDir() throws IOException {+ when(tempFileManagement.isStartupCleanup()).thenReturn(true);+ when(registry.contains(any(File.class))).thenReturn(false);++ Path leftover = Files.createDirectories(systemTempDir.resolve("jpdfium-left"));+ Files.writeString(leftover.resolve("jpdfium.dll"), "dll");+ Files.writeString(leftover.resolve(".lock"), "");+ backdate(leftover, 2L * 60 * 60 * 1000);++ withJvmTmpDir(tempDir.resolve("jvm-tmp-h"), cleanupService::init);++ assertThat(Files.exists(leftover)).isFalse();+ }++ @Test+ @DisplayName("reports how many extraction dirs it removed")+ void reportsRemovedCount() throws IOException {+ Path stale = Files.createDirectories(systemTempDir.resolve("jpdfium-old"));+ Files.writeString(stale.resolve("jpdfium.dll"), "dll");+ backdate(stale, 2L * 60 * 60 * 1000);+ AtomicInteger removed = new AtomicInteger(-1);++ withJvmTmpDir(+ tempDir.resolve("jvm-tmp-e"),+ () ->+ removed.set(+ (Integer)+ ReflectionTestUtils.invokeMethod(+ cleanupService, "cleanupStaleJpdfiumDirs")));++ assertThat(removed.get()).isEqualTo(1);+ }}@Nested@@ -253,6 +437,26 @@ class TempFileCleanupServiceMoreTest {assertThat(deleted).isGreaterThanOrEqualTo(1);assertThat(Files.exists(stale)).isFalse();}++ @Test+ @DisplayName("does not touch JPDFium extraction dirs or their lock")+ void skipsJpdfiumExtractionDirs() throws Exception {+ when(tempFileManagement.isCleanupSystemTemp()).thenReturn(true);+ when(tempFileManagement.getSystemTempDir()).thenReturn(systemTempDir.toString());+ when(registry.contains(any(File.class))).thenReturn(false);++ Path live = Files.createDirectories(systemTempDir.resolve("jpdfium-live"));+ Files.writeString(live.resolve("jpdfium.dll"), "dll");+ Path lock = Files.writeString(live.resolve(".lock"), "");+ // Older than the five-minute empty-file rule that would delete it.+ backdate(lock, 10L * 60 * 1000);++ ReflectionTestUtils.invokeMethod(+ cleanupService, "cleanupUnregisteredFiles", true, true, 3600000L);++ assertThat(Files.exists(lock)).isTrue();+ assertThat(Files.exists(live.resolve("jpdfium.dll"))).isTrue();+ }}@Nesteddiff --git a/app/core/src/main/java/stirling/software/SPDF/config/TauriProcessMonitor.java b/app/core/src/main/java/stirling/software/SPDF/config/TauriProcessMonitor.javaindex 2d5ca8b17c..76f4c99251 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/TauriProcessMonitor.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/TauriProcessMonitor.java@@ -1,9 +1,13 @@package stirling.software.SPDF.config;-import java.lang.management.ManagementFactory;+import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.LinkOption;+import java.nio.file.Path;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -16,10 +20,8 @@ import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;/**- * Monitor for Tauri parent process to detect orphaned Java backend processes. When running in Tauri- * mode, this component periodically checks if the parent Tauri process is still alive. If the- * parent process terminates unexpectedly, this will trigger a graceful shutdown of the Java backend- * to prevent orphaned processes.+ * Shuts the backend down when the Tauri desktop app exits. The app writes a sentinel file (works on+ * every platform, unlike signals); the parent PID check covers a crashed app.*/@Component@ConditionalOnProperty(name = "STIRLING_PDF_TAURI_MODE", havingValue = "true")@@ -27,10 +29,18 @@ public class TauriProcessMonitor {private static final Logger logger = LoggerFactory.getLogger(TauriProcessMonitor.class);+ // A stat every 250 ms keeps app close responsive at negligible cost.+ private static final long SENTINEL_POLL_MILLIS = 250;+ private static final long PARENT_POLL_SECONDS = 5;+ private static final LinkOption[] NO_LINKS = new LinkOption[0];+private final ApplicationContext applicationContext;- private String parentProcessId;+ private final AtomicBoolean monitoring = new AtomicBoolean(false);+ private final AtomicBoolean shutdownInitiated = new AtomicBoolean(false);++ private ProcessHandle parentHandle;+ private Path shutdownFile;private ScheduledExecutorService scheduler;- private volatile boolean monitoring = false;public TauriProcessMonitor(ApplicationContext applicationContext) {this.applicationContext = applicationContext;@@ -38,91 +48,103 @@ public class TauriProcessMonitor {@PostConstructpublic void init() {- parentProcessId = System.getenv("TAURI_PARENT_PID");-- if (parentProcessId != null && !parentProcessId.trim().isEmpty()) {- logger.info("Tauri mode detected. Parent process ID: {}", parentProcessId);- startMonitoring();- } else {- logger.warn(- "TAURI_PARENT_PID environment variable not found. Tauri process monitoring disabled.");- }- }-- private void startMonitoring() {- scheduler =- Executors.newSingleThreadScheduledExecutor(- r -> {- Thread t =- Thread.ofVirtual().name("tauri-process-monitor").unstarted(r);- return t;- });-- monitoring = true;-- // Check every 5 seconds- scheduler.scheduleAtFixedRate(this::checkParentProcess, 5, 5, TimeUnit.SECONDS);-- logger.info("Started monitoring parent Tauri process (PID: {})", parentProcessId);+ init(System.getenv("TAURI_PARENT_PID"), System.getenv("STIRLING_PDF_SHUTDOWN_FILE"));}- private void checkParentProcess() {- if (!monitoring) {+ /** Package-private so tests can supply the environment instead of mutating the JVM's. */+ void init(String parentPidEnv, String shutdownFilePathEnv) {+ Long parentPid = parseParentPid(parentPidEnv);+ parentHandle = parentPid == null ? null : ProcessHandle.of(parentPid).orElse(null);+ shutdownFile = parseShutdownFile(shutdownFilePathEnv);+ if (parentPid == null && shutdownFile == null) {+ logger.warn("Tauri mode without TAURI_PARENT_PID or STIRLING_PDF_SHUTDOWN_FILE");return;}-- try {- if (!isProcessAlive(parentProcessId)) {- logger.warn(- "Parent Tauri process (PID: {}) is no longer alive. Initiating graceful shutdown...",- parentProcessId);- initiateGracefulShutdown();- }- } catch (Exception e) {- logger.error("Error checking parent process status", e);+ // The sentinel is not deleted here: Tauri hands out a per-launch path and+ // sweeps older ones, so a file at this path is a stop request that may+ // have been written while this JVM was starting.+ if (parentPid != null && parentHandle == null) {+ // Tauri wrote the sentinel and exited while this JVM was starting; no+ // process is left to write it again, so the parent check is the only+ // trigger and the backend would otherwise outlive the app.+ logger.info("Tauri parent process {} is already gone; shutting down", parentPid);+ initiateGracefulShutdown("parent process already exited");+ return;}+ startMonitoring();}- private boolean isProcessAlive(String pid) {+ private static Long parseParentPid(String pid) {+ if (pid == null || pid.isBlank()) return null;try {- long processId = Long.parseLong(pid);+ return Long.parseLong(pid.trim());+ } catch (NumberFormatException e) {+ logger.error("Invalid TAURI_PARENT_PID: {}", pid);+ return null;+ }+ }- // Check if process exists using ProcessHandle (Java 9+)- return ProcessHandle.of(processId).isPresent();+ private static Path parseShutdownFile(String path) {+ return path == null || path.isBlank() ? null : Path.of(path);+ }- } catch (NumberFormatException e) {- logger.error("Invalid parent process ID format: {}", pid);- return false;- } catch (Exception e) {- logger.error("Error checking if process {} is alive", pid, e);- return false;+ private void startMonitoring() {+ scheduler =+ Executors.newSingleThreadScheduledExecutor(+ r -> Thread.ofVirtual().name("tauri-process-monitor").unstarted(r));+ monitoring.set(true);+ if (shutdownFile != null) {+ scheduler.scheduleWithFixedDelay(+ this::checkShutdownFile, 0, SENTINEL_POLL_MILLIS, TimeUnit.MILLISECONDS);}+ if (parentHandle != null) {+ scheduler.scheduleWithFixedDelay(+ this::checkParentProcess,+ PARENT_POLL_SECONDS,+ PARENT_POLL_SECONDS,+ TimeUnit.SECONDS);+ }+ logger.info(+ "Monitoring Tauri parent {} and shutdown file {}",+ parentHandle == null ? "-" : parentHandle.pid(),+ shutdownFile);}- private void initiateGracefulShutdown() {- monitoring = false;+ private void checkShutdownFile() {+ if (!monitoring.get() || shutdownFile == null) return;+ if (!Files.exists(shutdownFile, NO_LINKS)) return;+ try {+ Files.deleteIfExists(shutdownFile);+ } catch (IOException e) {+ logger.debug("Could not delete shutdown file: {}", e.getMessage());+ }+ initiateGracefulShutdown("shutdown file");+ }- logger.info("Orphaned Java backend detected. Shutting down gracefully...");+ private void checkParentProcess() {+ if (!monitoring.get() || parentHandle == null) return;+ if (!parentHandle.isAlive()) {+ initiateGracefulShutdown("parent process exit");+ }+ }- // Shutdown asynchronously to avoid blocking the monitor thread+ private void initiateGracefulShutdown(String reason) {+ if (!shutdownInitiated.compareAndSet(false, true)) return;+ monitoring.set(false);+ logger.info("Shutting down backend: {}", reason);Thread.ofVirtual().name("tauri-graceful-shutdown").start(() -> {try {- // Give a small delay to ensure logging completes- Thread.sleep(1000);-- if (applicationContext instanceof ConfigurableApplicationContext) {- ((ConfigurableApplicationContext) applicationContext).close();+ if (applicationContext+ instanceof ConfigurableApplicationContext context) {+ context.close();} else {- // Fallback to system exit- logger.warn(- "Unable to shutdown Spring context gracefully, using System.exit");System.exit(0);}} catch (Exception e) {- logger.error("Error during graceful shutdown", e);+ logger.error("Graceful shutdown failed", e);System.exit(1);}});@@ -130,29 +152,17 @@ public class TauriProcessMonitor {@PreDestroypublic void cleanup() {- monitoring = false;-- if (scheduler != null && !scheduler.isShutdown()) {- logger.info("Shutting down Tauri process monitor");- scheduler.shutdown();-- try {- if (!scheduler.awaitTermination(2, TimeUnit.SECONDS)) {- scheduler.shutdownNow();- }- } catch (InterruptedException e) {+ monitoring.set(false);+ if (scheduler == null || scheduler.isShutdown()) return;+ logger.info("Shutting down Tauri process monitor");+ scheduler.shutdown();+ try {+ if (!scheduler.awaitTermination(2, TimeUnit.SECONDS)) {scheduler.shutdownNow();- Thread.currentThread().interrupt();}- }- }-- /** Get the current Java process ID for logging/debugging purposes */- public static String getCurrentProcessId() {- try {- return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];- } catch (Exception e) {- return "unknown";+ } catch (InterruptedException e) {+ scheduler.shutdownNow();+ Thread.currentThread().interrupt();}}}diff --git a/app/core/src/test/java/stirling/software/SPDF/config/TauriProcessMonitorTest.java b/app/core/src/test/java/stirling/software/SPDF/config/TauriProcessMonitorTest.javaindex 88a363deb9..d68643cf5b 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/TauriProcessMonitorTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/TauriProcessMonitorTest.java@@ -2,8 +2,8 @@ package stirling.software.SPDF.config;import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.mockStatic;import static org.mockito.Mockito.never;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;@@ -11,34 +11,26 @@ import static org.mockito.Mockito.when;import java.lang.reflect.Field;import java.lang.reflect.Method;-import java.util.Optional;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.concurrent.CountDownLatch;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;-import org.mockito.MockedStatic;+import org.junit.jupiter.api.io.TempDir;import org.springframework.context.ApplicationContext;import org.springframework.context.ConfigurableApplicationContext;@DisplayName("TauriProcessMonitor")class TauriProcessMonitorTest {- private static Object invokePrivate(TauriProcessMonitor monitor, String name, Object... args)- throws Exception {- Method method = findMethod(name);+ private static Object invoke(TauriProcessMonitor monitor, String name) throws Exception {+ Method method = TauriProcessMonitor.class.getDeclaredMethod(name);method.setAccessible(true);- return method.invoke(monitor, args);- }-- private static Method findMethod(String name) {- for (Method m : TauriProcessMonitor.class.getDeclaredMethods()) {- if (m.getName().equals(name)) {- return m;- }- }- throw new IllegalStateException("Method not found: " + name);+ return method.invoke(monitor);}private static void setField(TauriProcessMonitor monitor, String name, Object value)@@ -54,230 +46,182 @@ class TauriProcessMonitorTest {return field.get(monitor);}- @Nested- @DisplayName("getCurrentProcessId")- class CurrentProcessId {-- @Test- @DisplayName("returns a non-blank PID string")- void returnsPid() {- assertThat(TauriProcessMonitor.getCurrentProcessId()).isNotBlank();- }+ private static AtomicBoolean monitoringFlag(TauriProcessMonitor monitor) throws Exception {+ return (AtomicBoolean) getField(monitor, "monitoring");}- @Nested- @DisplayName("init")- class Init {-- // System.getenv cannot be mocked (java.base), so init() is exercised against the real- // environment, which has no TAURI_PARENT_PID; the present-PID path is driven directly- // through startMonitoring().-- @Test- @DisplayName("startMonitoring flips monitoring on and creates a scheduler")- void startMonitoringSchedulesTask() throws Exception {- ApplicationContext ctx = mock(ApplicationContext.class);- TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);- setField(monitor, "parentProcessId", "12345");-- try {- invokePrivate(monitor, "startMonitoring");-- assertThat((Boolean) getField(monitor, "monitoring")).isTrue();- assertThat(getField(monitor, "scheduler")).isNotNull();- assertThat((String) getField(monitor, "parentProcessId")).isEqualTo("12345");- } finally {- // Stop the scheduler thread created by startMonitoring.- monitor.cleanup();- }- }+ private static CountDownLatch closingContext(ConfigurableApplicationContext ctx) {+ CountDownLatch closed = new CountDownLatch(1);+ doAnswer(+ invocation -> {+ closed.countDown();+ return null;+ })+ .when(ctx)+ .close();+ return closed;}- @Nested- @DisplayName("isProcessAlive")- class IsProcessAlive {-- @Test- @DisplayName("returns true when ProcessHandle reports the PID present")- void aliveWhenPresent() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));-- try (MockedStatic<ProcessHandle> ph = mockStatic(ProcessHandle.class)) {- ph.when(() -> ProcessHandle.of(999L))- .thenReturn(Optional.of(mock(ProcessHandle.class)));- Object result = invokePrivate(monitor, "isProcessAlive", "999");- assertThat((Boolean) result).isTrue();- }- }-- @Test- @DisplayName("returns false when ProcessHandle reports the PID absent")- void deadWhenAbsent() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));-- try (MockedStatic<ProcessHandle> ph = mockStatic(ProcessHandle.class)) {- ph.when(() -> ProcessHandle.of(999L)).thenReturn(Optional.empty());- Object result = invokePrivate(monitor, "isProcessAlive", "999");- assertThat((Boolean) result).isFalse();- }- }+ @Test+ @DisplayName("init without Tauri env disables monitoring")+ void initWithoutEnvDisablesMonitoring() throws Exception {+ TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));- @Test- @DisplayName("returns false for a non-numeric PID")- void falseForInvalidPid() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));+ monitor.init();- Object result = invokePrivate(monitor, "isProcessAlive", "not-a-number");- assertThat((Boolean) result).isFalse();- }+ assertThat(monitoringFlag(monitor)).isFalse();+ assertThat(getField(monitor, "scheduler")).isNull();}- @Nested- @DisplayName("checkParentProcess")- class CheckParentProcess {-- @Test- @DisplayName("returns early when monitoring is off")- void earlyReturnWhenNotMonitoring() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));- setField(monitor, "monitoring", false);-- // Should not throw even though parentProcessId is null.- invokePrivate(monitor, "checkParentProcess");- }+ @Test+ @DisplayName("init with a parent that already exited shuts the backend down")+ void initWithGoneParentShutsDown(@TempDir Path tmp) throws Exception {+ ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);+ CountDownLatch closed = closingContext(ctx);+ TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);+ Path sentinel = Files.writeString(tmp.resolve("backend.stop"), "stop");- @Test- @DisplayName("triggers graceful shutdown when the parent process is dead")- void shutsDownWhenParentDead() throws Exception {- ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);- TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);- setField(monitor, "monitoring", true);- setField(monitor, "parentProcessId", "999");+ monitor.init(String.valueOf(Long.MAX_VALUE), sentinel.toString());- try (MockedStatic<ProcessHandle> ph = mockStatic(ProcessHandle.class)) {- ph.when(() -> ProcessHandle.of(999L)).thenReturn(Optional.empty());+ assertThat(closed.await(2, TimeUnit.SECONDS)).isTrue();+ // The stop request stays on disk for Tauri's next-launch sweep.+ assertThat(Files.exists(sentinel)).isTrue();+ assertThat(getField(monitor, "scheduler")).isNull();+ }- invokePrivate(monitor, "checkParentProcess");+ @Test+ @DisplayName("init with an unparsable parent PID still watches the sentinel")+ void initWithInvalidParentPidKeepsWatching(@TempDir Path tmp) throws Exception {+ TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));- // initiateGracefulShutdown flips monitoring off and spawns an async close.- // The async close runs after a hardcoded 1s sleep, so we assert only the- // immediate, deterministic effect to keep the test fast.- assertThat((Boolean) getField(monitor, "monitoring")).isFalse();- }+ monitor.init("not-a-pid", tmp.resolve("absent.stop").toString());+ try {+ assertThat(monitoringFlag(monitor)).isTrue();+ assertThat(getField(monitor, "scheduler")).isNotNull();+ } finally {+ monitor.cleanup();}+ }- @Test- @DisplayName("does nothing when the parent process is still alive")- void noShutdownWhenParentAlive() throws Exception {- ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);- TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);- setField(monitor, "monitoring", true);- setField(monitor, "parentProcessId", "999");+ @Test+ @DisplayName("init with a live parent keeps monitoring")+ void initWithLiveParentKeepsMonitoring(@TempDir Path tmp) throws Exception {+ TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));++ monitor.init(+ String.valueOf(ProcessHandle.current().pid()),+ tmp.resolve("absent.stop").toString());+ try {+ assertThat(monitoringFlag(monitor)).isTrue();+ assertThat(getField(monitor, "parentHandle")).isNotNull();+ } finally {+ monitor.cleanup();+ }+ }- try (MockedStatic<ProcessHandle> ph = mockStatic(ProcessHandle.class)) {- ph.when(() -> ProcessHandle.of(999L))- .thenReturn(Optional.of(mock(ProcessHandle.class)));+ @Test+ @DisplayName("sentinel file triggers a graceful context close")+ void sentinelTriggersShutdown(@TempDir Path tmp) throws Exception {+ ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);+ CountDownLatch closed = closingContext(ctx);+ TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);+ Path sentinel = Files.writeString(tmp.resolve("backend.stop"), "stop");+ setField(monitor, "shutdownFile", sentinel);+ setField(monitor, "monitoring", new AtomicBoolean(true));- invokePrivate(monitor, "checkParentProcess");+ invoke(monitor, "checkShutdownFile");- assertThat((Boolean) getField(monitor, "monitoring")).isTrue();- }- verify(ctx, never()).close();- }+ assertThat(closed.await(2, TimeUnit.SECONDS)).isTrue();+ assertThat(Files.exists(sentinel)).isFalse();}- @Nested- @DisplayName("initiateGracefulShutdown")- class InitiateGracefulShutdown {-- @Test- @DisplayName("closes a ConfigurableApplicationContext asynchronously")- void closesConfigurableContext() throws Exception {- ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);- TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);- setField(monitor, "monitoring", true);+ @Test+ @DisplayName("missing sentinel leaves the backend running")+ void absentSentinelKeepsRunning(@TempDir Path tmp) throws Exception {+ TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));+ setField(monitor, "shutdownFile", tmp.resolve("absent.stop"));+ setField(monitor, "monitoring", new AtomicBoolean(true));- invokePrivate(monitor, "initiateGracefulShutdown");+ invoke(monitor, "checkShutdownFile");- // The async close runs after a hardcoded 1s sleep; assert only the immediate effect.- assertThat((Boolean) getField(monitor, "monitoring")).isFalse();- }+ assertThat(monitoringFlag(monitor)).isTrue();}- @Nested- @DisplayName("cleanup")- class Cleanup {-- @Test- @DisplayName("is a no-op when no scheduler was created")- void noOpWithoutScheduler() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));+ @Test+ @DisplayName("dead parent process triggers a graceful close")+ void deadParentTriggersShutdown() throws Exception {+ ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);+ CountDownLatch closed = closingContext(ctx);+ TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);+ ProcessHandle parent = mock(ProcessHandle.class);+ when(parent.isAlive()).thenReturn(false);+ setField(monitor, "parentHandle", parent);+ setField(monitor, "monitoring", new AtomicBoolean(true));- // scheduler is null by default; cleanup must not throw.- monitor.cleanup();+ invoke(monitor, "checkParentProcess");- assertThat((Boolean) getField(monitor, "monitoring")).isFalse();- }+ assertThat(closed.await(2, TimeUnit.SECONDS)).isTrue();+ }- @Test- @DisplayName("shuts down an active scheduler")- void shutsDownActiveScheduler() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));- ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);- when(scheduler.isShutdown()).thenReturn(false);- when(scheduler.awaitTermination(eq(2L), eq(TimeUnit.SECONDS))).thenReturn(true);- setField(monitor, "scheduler", scheduler);- setField(monitor, "monitoring", true);+ @Test+ @DisplayName("live parent process leaves the backend running")+ void liveParentKeepsRunning() throws Exception {+ ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);+ TauriProcessMonitor monitor = new TauriProcessMonitor(ctx);+ ProcessHandle parent = mock(ProcessHandle.class);+ when(parent.isAlive()).thenReturn(true);+ setField(monitor, "parentHandle", parent);+ setField(monitor, "monitoring", new AtomicBoolean(true));- monitor.cleanup();+ invoke(monitor, "checkParentProcess");- verify(scheduler, times(1)).shutdown();- assertThat((Boolean) getField(monitor, "monitoring")).isFalse();- }+ assertThat(monitoringFlag(monitor)).isTrue();+ verify(ctx, never()).close();+ }- @Test- @DisplayName("forces shutdownNow when awaitTermination times out")- void forcesShutdownNowOnTimeout() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));- ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);- when(scheduler.isShutdown()).thenReturn(false);- when(scheduler.awaitTermination(eq(2L), eq(TimeUnit.SECONDS))).thenReturn(false);- setField(monitor, "scheduler", scheduler);+ @Test+ @DisplayName("cleanup shuts down an active scheduler")+ void cleanupShutsScheduler() throws Exception {+ TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));+ ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);+ when(scheduler.isShutdown()).thenReturn(false);+ when(scheduler.awaitTermination(eq(2L), eq(TimeUnit.SECONDS))).thenReturn(true);+ setField(monitor, "scheduler", scheduler);+ setField(monitor, "monitoring", new AtomicBoolean(true));- monitor.cleanup();+ monitor.cleanup();- verify(scheduler, times(1)).shutdown();- verify(scheduler, times(1)).shutdownNow();- }+ verify(scheduler, times(1)).shutdown();+ assertThat(monitoringFlag(monitor)).isFalse();+ }- @Test- @DisplayName("restores interrupt flag when awaitTermination is interrupted")- void handlesInterruptedException() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));- ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);- when(scheduler.isShutdown()).thenReturn(false);- when(scheduler.awaitTermination(eq(2L), eq(TimeUnit.SECONDS)))- .thenThrow(new InterruptedException("boom"));- setField(monitor, "scheduler", scheduler);+ @Test+ @DisplayName("cleanup forces shutdownNow when awaitTermination times out")+ void cleanupForcesShutdownNow() throws Exception {+ TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));+ ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);+ when(scheduler.isShutdown()).thenReturn(false);+ when(scheduler.awaitTermination(eq(2L), eq(TimeUnit.SECONDS))).thenReturn(false);+ setField(monitor, "scheduler", scheduler);- monitor.cleanup();+ monitor.cleanup();- verify(scheduler, times(1)).shutdownNow();- // Clear the interrupt flag we just set so it does not leak to other tests.- assertThat(Thread.interrupted()).isTrue();- }+ verify(scheduler, times(1)).shutdownNow();+ }- @Test- @DisplayName("skips shutdown when scheduler already terminated")- void skipsAlreadyShutdownScheduler() throws Exception {- TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));- ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);- when(scheduler.isShutdown()).thenReturn(true);- setField(monitor, "scheduler", scheduler);+ @Test+ @DisplayName("cleanup restores the interrupt flag")+ void cleanupRestoresInterrupt() throws Exception {+ TauriProcessMonitor monitor = new TauriProcessMonitor(mock(ApplicationContext.class));+ ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);+ when(scheduler.isShutdown()).thenReturn(false);+ when(scheduler.awaitTermination(eq(2L), eq(TimeUnit.SECONDS)))+ .thenThrow(new InterruptedException("boom"));+ setField(monitor, "scheduler", scheduler);- monitor.cleanup();+ monitor.cleanup();- verify(scheduler, never()).shutdown();- }+ verify(scheduler, times(1)).shutdownNow();+ assertThat(Thread.interrupted()).isTrue();}}diff --git a/build.gradle b/build.gradleindex 44c4c1329c..caaa02a79b 100644--- a/build.gradle+++ b/build.gradle@@ -42,7 +42,7 @@ ext {bucket4jVersion = "8.19.0"archunitVersion = "1.5.0"batikVersion = "1.19"- jpdfiumVersion = "1.1.4"+ jpdfiumVersion = "1.1.5"jwtVersion = "0.13.0"awsSdkVersion = "2.51.3"jschVersion = "2.28.7"diff --git a/frontend/editor/src-tauri/src/commands/backend.rs b/frontend/editor/src-tauri/src/commands/backend.rsindex 6db0a4c1ac..28c406dda5 100644--- a/frontend/editor/src-tauri/src/commands/backend.rs+++ b/frontend/editor/src-tauri/src/commands/backend.rs@@ -1,14 +1,39 @@use tauri_plugin_shell::ShellExt;use tauri::Manager;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Mutex;use std::path::{Path, PathBuf};+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use crate::utils::{add_log, app_data_dir};use crate::state::connection_state::{AppConnectionState, ConnectionMode};+/// Removes shutdown markers left by previous sessions. The current path cannot+/// exist yet, so it is never a sweep target.+fn sweep_stale_shutdown_files(work_dir: &Path, keep: &Path) {+ let Ok(entries) = std::fs::read_dir(work_dir) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path == keep {+ continue;+ }+ let Some(name) = path.file_name().and_then(|name| name.to_str()) else {+ continue;+ };+ if name.starts_with(".backend-stop") {+ let _ = std::fs::remove_file(&path);+ }+ }+}+// Store backend process handle and port globallystatic BACKEND_PROCESS: Mutex<Option<tauri_plugin_shell::process::CommandChild>> = Mutex::new(None);static BACKEND_STARTING: Mutex<bool> = Mutex::new(false);static BACKEND_PORT: Mutex<Option<u16>> = Mutex::new(None);+// Set by the event loop when the backend exits, so cleanup can wait for it.+static BACKEND_EXITED: AtomicBool = AtomicBool::new(true);+static BACKEND_SHUTDOWN_FILE: Mutex<Option<PathBuf>> = Mutex::new(None);// Helper function to reset starting flagfn reset_starting_flag() {@@ -261,6 +286,21 @@ fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &}}+ // Sentinel for a graceful stop on every platform; signals are not portable.+ // The name is per launch so a marker a previous session failed to clear can+ // never stop this one; stale markers are swept here, before this launch+ // owns one.+ let shutdown_file = work_dir.join(format!(+ ".backend-stop-{}-{}",+ std::process::id(),+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|elapsed| elapsed.as_millis())+ .unwrap_or(0)+ ));+ sweep_stale_shutdown_files(&work_dir, &shutdown_file);+ *BACKEND_SHUTDOWN_FILE.lock().unwrap() = Some(shutdown_file.clone());+let sidecar_command = app.shell().command(java_path.to_str().unwrap())@@ -269,7 +309,8 @@ fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &.env("TAURI_PARENT_PID", std::process::id().to_string()).env("STIRLING_PDF_CONFIG_DIR", config_dir.to_str().unwrap()).env("STIRLING_PDF_LOG_DIR", log_dir.to_str().unwrap())- .env("STIRLING_PDF_WORK_DIR", work_dir.to_str().unwrap());+ .env("STIRLING_PDF_WORK_DIR", work_dir.to_str().unwrap())+ .env("STIRLING_PDF_SHUTDOWN_FILE", shutdown_file.to_str().unwrap());add_log("⚙️ Starting backend with bundled JRE...".to_string());@@ -281,7 +322,7 @@ fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &error_msg})?;- // Store the process handle+ BACKEND_EXITED.store(false, Ordering::Release);{let mut process_guard = BACKEND_PROCESS.lock().unwrap();*process_guard = Some(child);@@ -366,7 +407,7 @@ fn monitor_backend_output(mut rx: tauri::async_runtime::Receiver<tauri_plugin_sh_ => println!("❌ Process terminated with code: {}", code),}}- // Clear the stored process handle+ BACKEND_EXITED.store(true, Ordering::Release);let mut process_guard = BACKEND_PROCESS.lock().unwrap();*process_guard = None;}@@ -467,21 +508,28 @@ pub fn get_backend_port() -> Option<u16> {*port_guard}-// Cleanup function to stop backend on app exit+// Stop the backend on app exit: request a graceful Spring shutdown, then force.pub fn cleanup_backend() {- let mut process_guard = BACKEND_PROCESS.lock().unwrap();- if let Some(child) = process_guard.take() {- let pid = child.pid();- add_log(format!("🧹 App shutting down, cleaning up backend process (PID: {})", pid));-- match child.kill() {- Ok(_) => {- add_log(format!("✅ Backend process (PID: {}) terminated during cleanup", pid));- }- Err(e) => {- add_log(format!("❌ Failed to terminate backend process during cleanup: {}", e));- println!("❌ Failed to terminate backend process during cleanup: {}", e);- }+ let child = BACKEND_PROCESS.lock().unwrap().take();+ let Some(child) = child else { return };+ let pid = child.pid();+ add_log(format!("App shutting down, stopping backend (PID: {})", pid));++ if let Some(path) = BACKEND_SHUTDOWN_FILE.lock().unwrap().clone() {+ if let Err(e) = std::fs::write(&path, b"stop") {+ add_log(format!("Could not write shutdown file: {}", e));}}++ let deadline = Instant::now() + Duration::from_secs(10);+ while !BACKEND_EXITED.load(Ordering::Acquire) && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(50));+ }++ if BACKEND_EXITED.load(Ordering::Acquire) {+ add_log(format!("Backend (PID: {}) stopped gracefully", pid));+ } else {+ add_log(format!("Backend (PID: {}) did not stop in time, killing", pid));+ let _ = child.kill();+ }}diff --git a/testing/test.sh b/testing/test.shindex 9eafea6f26..f2488bd750 100644--- a/testing/test.sh+++ b/testing/test.sh@@ -465,8 +465,8 @@ compare_file_lists() {echo "New files created during test:"cat "${diff_file}.added" | sed 's/^> //'- # Exclude JPDFium native cache + merge seed temp files- # (both deleteOnExit-registered, not leaks).+ # Exclude JPDFium extraction dirs: older versions leak one per JVM+ # on Windows; TempFileCleanupService sweeps stale ones at startup.# Also exclude LibreOffice instance folders, X11 locks, and dconf caches# which are transient and normal during container operation.grep -i "tmp\|temp" "${diff_file}.added" \