Skip to content

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

Recognise the failures nobody can act on (#8068)

EthanHealy0139d96355a44b
diff --git a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
index 3cbfaf9b33..99d1dac96e 100644
--- a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
@@ -656,9 +656,9 @@ public class ExceptionUtils {
return new IllegalArgumentException(message);
}
- public static IllegalArgumentException createFileNullOrEmptyException() {
+ public static FileValidationException createFileNullOrEmptyException() {
String message = getMessage(ErrorCode.FILE_NULL_OR_EMPTY);
- return new IllegalArgumentException(message);
+ return new FileValidationException(message, ErrorCode.FILE_NULL_OR_EMPTY.getCode());
}
public static IllegalArgumentException createFileNoNameException() {
@@ -712,6 +712,30 @@ public class ExceptionUtils {
return new ComplianceNotMetException(message, ErrorCode.COMPLIANCE_NOT_MET.getCode());
}
+ /** Raised once every available repair tool has tried the document and declined it. */
+ public static PdfUnrepairableException createPdfUnrepairableException() {
+ return new PdfUnrepairableException(
+ getMessage(ErrorCode.PDF_UNREPAIRABLE), ErrorCode.PDF_UNREPAIRABLE.getCode());
+ }
+
+ /**
+ * A step refused its input on type alone, before running.
+ *
+ * @param actual the extension, never the filename: this message is persisted on a failure
+ * record, which holds no document names
+ */
+ public static StepInputTypeException createStepInputTypeException(
+ String operation, List<String> accepted, String actual) {
+ String message =
+ getMessage(
+ ErrorCode.STEP_INPUT_TYPE_REJECTED.getMessageKey(),
+ ErrorCode.STEP_INPUT_TYPE_REJECTED.getDefaultMessage(),
+ operation,
+ accepted,
+ actual);
+ return new StepInputTypeException(message, ErrorCode.STEP_INPUT_TYPE_REJECTED.getCode());
+ }
+
/** Create system requirement exceptions. */
public static FfmpegRequiredException createFfmpegRequiredException() {
String message = getMessage(ErrorCode.FFMPEG_REQUIRED);
@@ -1046,16 +1070,18 @@ public class ExceptionUtils {
public static IOException handlePdfException(IOException e, String context) {
requireNonNull(e, "exception");
- if (PdfErrorUtils.isCorruptedPdfError(e)) {
- return createPdfCorruptedException(context, e);
+ // Most specific first: corruption's patterns cover almost anything PDFBox gives up on,
+ // so testing it earlier reported every document that would not decrypt as damaged.
+ if (isPasswordError(e)) {
+ return createPdfPasswordException(e);
}
if (isEncryptionError(e)) {
return createPdfEncryptionException(e);
}
- if (isPasswordError(e)) {
- return createPdfPasswordException(e);
+ if (PdfErrorUtils.isCorruptedPdfError(e)) {
+ return createPdfCorruptedException(context, e);
}
return e; // Return original exception if no specific handling needed
@@ -1231,6 +1257,20 @@ public class ExceptionUtils {
// profile and failing rules.
COMPLIANCE_NOT_MET("E074", "error.complianceNotMet", "{0}"),
+ // Every repair strategy declined it. Distinct from PDF_CORRUPTED, which says a document
+ // is damaged: this says the damage has already survived the tools that fix damage.
+ PDF_UNREPAIRABLE(
+ "E076",
+ "error.pdfUnrepairable",
+ "This document is damaged in a way the repair tools cannot fix."),
+
+ // Raised before a step runs, by whoever knows both what the step accepts and what it was
+ // handed. Distinct from PDF_NOT_PDF, which speaks only for steps that want a PDF.
+ STEP_INPUT_TYPE_REJECTED(
+ "E075",
+ "error.stepInputTypeRejected",
+ "Step {0} accepts {1} but received a ''{2}'' file"),
+
// System errors
MD5_ALGORITHM("E080", "error.md5Algorithm", "MD5 algorithm not available"),
OUT_OF_MEMORY_DPI(
@@ -1299,6 +1339,20 @@ public class ExceptionUtils {
}
}
+ /** Exception thrown when every repair strategy has declined a damaged document. */
+ public static class PdfUnrepairableException extends BaseAppException {
+ public PdfUnrepairableException(String message, String errorCode) {
+ super(message, null, errorCode);
+ }
+ }
+
+ /** Exception thrown when a step is handed a file of a type it does not accept. */
+ public static class StepInputTypeException extends BaseAppException {
+ public StepInputTypeException(String message, String errorCode) {
+ super(message, null, errorCode);
+ }
+ }
+
/** Exception thrown when FFmpeg is not available on the host system. */
public static class FfmpegRequiredException extends BaseAppException {
public FfmpegRequiredException(String message, String errorCode) {
@@ -1363,6 +1417,16 @@ public class ExceptionUtils {
}
}
+ /**
+ * A submitted file that fails a validation its caller could correct, such as arriving empty.
+ * Coded, so the refusal reaches a failure record rather than the handler that attaches none.
+ */
+ public static class FileValidationException extends BaseValidationException {
+ public FileValidationException(String message, String errorCode) {
+ super(message, errorCode);
+ }
+ }
+
/** Exception thrown when a PDF file is corrupted or damaged. */
public static class PdfCorruptedException extends BaseAppException {
public PdfCorruptedException(String message, Throwable cause, String errorCode) {
diff --git a/app/common/src/main/java/stirling/software/common/util/PdfErrorUtils.java b/app/common/src/main/java/stirling/software/common/util/PdfErrorUtils.java
index aeda114c99..e11e2adb6d 100644
--- a/app/common/src/main/java/stirling/software/common/util/PdfErrorUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/PdfErrorUtils.java
@@ -34,7 +34,8 @@ public class PdfErrorUtils {
private static boolean isCorruptedPdfError(String message) {
if (message == null) return false;
- // Check for common corruption indicators
+ // Structural damage only: a failed decryption is matched by isEncryptionError, and
+ // listing it here too let whichever check ran first decide the kind.
return message.contains("Missing root object specification")
|| message.contains("Header doesn't contain versioninfo")
|| message.contains("Expected trailer")
@@ -47,9 +48,6 @@ public class PdfErrorUtils {
|| message.contains("ICCBased colorspace array must have a stream")
|| message.contains("1-based index not found")
|| message.contains("Invalid dictionary, found:")
- || message.contains("AES initialization vector not fully read")
- || message.contains("BadPaddingException")
- || message.contains("Given final block not properly padded")
|| message.contains("End-of-File, expected line");
}
}
diff --git a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.java
index 2584481caf..4ea948b189 100644
--- a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsTest.java
@@ -234,6 +234,39 @@ class ExceptionUtilsTest {
}
}
+ @Test
+ void aFailedDecryptionIsEncryptionRatherThanCorruption() {
+ // Unmocked, in PDFBox's own wording: these were listed as corruption indicators too,
+ // and corruption was tested first, so an undecryptable file read as damaged.
+ for (String message :
+ new String[] {
+ "BadPaddingException",
+ "Given final block not properly padded",
+ "AES initialization vector not fully read"
+ }) {
+ IOException result = ExceptionUtils.handlePdfException(new IOException(message));
+ assertTrue(
+ result.getMessage().contains("corrupted encryption data"),
+ message + " should read as an encryption failure");
+ }
+ }
+
+ @Test
+ void structuralDamageIsStillCorruption() {
+ IOException result =
+ ExceptionUtils.handlePdfException(
+ new IOException("Error: End-of-File, expected line at offset 45"));
+ assertTrue(result.getMessage().contains("corrupted or damaged"));
+ }
+
+ @Test
+ void aMissingPasswordOutranksBoth() {
+ IOException result =
+ ExceptionUtils.handlePdfException(
+ new IOException("PDF contains an encryption dictionary"));
+ assertTrue(result.getMessage().contains("passworded"));
+ }
+
@Test
void testHandlePdfExceptionWhenNoSpecialError() {
IOException original = new IOException("something else");
diff --git a/app/common/src/test/java/stirling/software/common/util/PdfErrorUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/PdfErrorUtilsTest.java
index 5e49910130..9937603a76 100644
--- a/app/common/src/test/java/stirling/software/common/util/PdfErrorUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/PdfErrorUtilsTest.java
@@ -25,9 +25,6 @@ class PdfErrorUtilsTest {
"ICCBased colorspace array must have a stream",
"1-based index not found",
"Invalid dictionary, found:",
- "AES initialization vector not fully read",
- "BadPaddingException",
- "Given final block not properly padded",
"End-of-File, expected line"
})
void isCorruptedPdfError_ioException_corruptionIndicators_returnsTrue(String message) {
@@ -35,6 +32,19 @@ class PdfErrorUtilsTest {
assertTrue(PdfErrorUtils.isCorruptedPdfError(e));
}
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "AES initialization vector not fully read",
+ "BadPaddingException",
+ "Given final block not properly padded"
+ })
+ void isCorruptedPdfError_decryptionFailures_returnsFalse(String message) {
+ // Matched by ExceptionUtils#isEncryptionError instead. Claiming them here too let
+ // whichever check ran first decide the kind, and corruption ran first.
+ assertFalse(PdfErrorUtils.isCorruptedPdfError(new IOException(message)));
+ }
+
@ParameterizedTest
@ValueSource(
strings = {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RepairController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RepairController.java
index 7c74c85d09..afa0d26b5c 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RepairController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/RepairController.java
@@ -100,17 +100,25 @@ public class RepairController {
if (!repairSuccess && isQpdfEnabled()) {
List<String> qpdfCommand = new ArrayList<>();
qpdfCommand.add("qpdf");
- qpdfCommand.add("--replace-input"); // Automatically fixes problems it can
+ // No --replace-input: it edits the input in place and takes no output path, so
+ // passing one made every fallback die before qpdf read a byte.
qpdfCommand.add("--qdf"); // Linearizes and normalizes PDF structure
qpdfCommand.add("--object-streams=disable"); // Can help with some corruptions
qpdfCommand.add(tempInputFile.getPath().toString());
qpdfCommand.add(tempOutputFile.getPath().toString());
- ProcessExecutorResult qpdfResult =
- ProcessExecutor.getInstance(ProcessExecutor.Processes.QPDF)
- .runCommandWithOutputHandling(qpdfCommand);
-
- repairSuccess = true;
+ try {
+ ProcessExecutorResult qpdfResult =
+ ProcessExecutor.getInstance(ProcessExecutor.Processes.QPDF)
+ .runCommandWithOutputHandling(qpdfCommand);
+
+ // qpdf exits 3 for warnings it recovered from, which is a repaired file.
+ repairSuccess = qpdfResult.getRc() == 0 || qpdfResult.getRc() == 3;
+ } catch (IOException | RuntimeException e) {
+ // A non-zero exit throws rather than returning, and its stderr names temp
+ // paths. An interrupt is left to propagate: a cancelled job is not a refusal.
+ log.warn("QPDF repair failed: ", e);
+ }
}
// Use PDFBox as last resort if no external tools are available
@@ -122,9 +130,9 @@ public class RepairController {
repairSuccess = true;
}
} else {
- throw ExceptionUtils.createFileProcessingException(
- "PDF repair",
- new IOException("PDF repair failed with available tools"));
+ // Coded, so the caller can say why rather than showing a bare 500: every tool
+ // present has tried this document and declined it.
+ throw ExceptionUtils.createPdfUnrepairableException();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RepairControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RepairControllerMoreTest.java
index f564dafb11..bd7e29415b 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RepairControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/RepairControllerMoreTest.java
@@ -40,6 +40,8 @@ import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.ExceptionUtils;
+import stirling.software.common.util.ExceptionUtils.PdfUnrepairableException;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFileManager;
@@ -275,25 +277,29 @@ class RepairControllerMoreTest {
}
@Test
- @DisplayName("qpdf IOException propagates to the caller")
- void qpdfIOExceptionPropagates() throws Exception {
+ @DisplayName("a qpdf refusal is reported as unrepairable, not passed on verbatim")
+ void qpdfIOExceptionBecomesCoded() throws Exception {
when(endpointConfiguration.isGroupEnabled("Ghostscript")).thenReturn(false);
when(endpointConfiguration.isGroupEnabled("qpdf")).thenReturn(true);
try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
ProcessExecutor qpdfExecutor = mock(ProcessExecutor.class);
when(qpdfExecutor.runCommandWithOutputHandling(any()))
- .thenThrow(new IOException("qpdf failed hard"));
+ .thenThrow(new IOException("qpdf failed hard on /tmp/repair123.pdf"));
mockedFactory
.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.QPDF))
.thenReturn(qpdfExecutor);
- IOException thrown =
+ PdfUnrepairableException thrown =
assertThrows(
- IOException.class,
+ PdfUnrepairableException.class,
() -> repairController.repairPdf(pdfFileFrom(inputPdf(1))));
- assertEquals("qpdf failed hard", thrown.getMessage());
+
+ assertEquals(
+ ExceptionUtils.ErrorCode.PDF_UNREPAIRABLE.getCode(), thrown.getErrorCode());
+ // qpdf names temp paths in its stderr, and a notification is persisted.
+ assertFalse(thrown.getMessage().contains("/tmp/repair123.pdf"));
}
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
index 496fc234b5..605b18165a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
@@ -77,6 +77,122 @@ public enum FailureKind {
global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+ /**
+ * Damage the repair tools have already declined, so the row stops offering a fix that has been
+ * tried and refused.
+ */
+ INPUT_UNREPAIRABLE(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.PERMANENT,
+ FailureScope.FILE,
+ errorCodes("E076"),
+ fallback("This document is damaged beyond what the repair tools can fix."),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
+ /**
+ * The format checks a tool runs before it reads anything: a PDF tool handed a .docx, a comic
+ * reader handed something that is not the archive it names.
+ */
+ INPUT_WRONG_TYPE(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_FILE_FIX,
+ FailureScope.FILE,
+ errorCodes("E006", "E014", "E018", "E061", "E075"),
+ fallback("This document is not a format the step can open, so it could not be read."),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(OPEN_IN_TOOL, OWNER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
+ /**
+ * The file is the type it claims and still will not open: an unopenable RAR or ZIP, an EML that
+ * will not parse, image bytes no decoder accepts.
+ *
+ * <p>Deliberately does not offer REPAIR despite reading like {@link #INPUT_CORRUPTED}. Repair
+ * is a PDF tool and none of these codes comes from a PDF.
+ */
+ INPUT_UNREADABLE(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_FILE_FIX,
+ FailureScope.FILE,
+ errorCodes("E010", "E015", "E021", "E034"),
+ fallback("This document could not be opened, so the pipeline could not read it."),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(OPEN_IN_TOOL, OWNER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
+ /** Opened fine and holds nothing to work on: no pages, no images, no bytes. */
+ INPUT_EMPTY(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.PERMANENT,
+ FailureScope.FILE,
+ errorCodes("E005", "E012", "E016", "E020", "E032"),
+ fallback("This document has no content in it, so there was nothing to work on."),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(OPEN_IN_TOOL, OWNER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
+ /**
+ * The run never got hold of the document: the id resolves to nothing, or the upload arrived
+ * with no name to address it by.
+ */
+ INPUT_UNAVAILABLE(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.PERMANENT,
+ FailureScope.FILE,
+ errorCodes("E030", "E033"),
+ fallback("The document behind this run could not be reached, so it was not processed."),
+ // No VIEW_FILE and no OPEN_IN_TOOL: both would open a tool on a document that is not
+ // there, which is the failure itself.
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
+ /**
+ * A binary the step shells out to is absent from this deployment. Scoped to the server, not the
+ * file, because it fails every run that reaches the step and one incident says that better than
+ * one per document.
+ */
+ TOOL_NOT_INSTALLED(
+ FailureStage.INTERNAL,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_SERVER_FIX,
+ FailureScope.SERVER,
+ errorCodes("E042", "E062", "E063", "E080"),
+ fallback("This server is missing software the step needs, so it could not be run."),
+ // Nothing for an owner to press: their document is fine, and a retry fails the same
+ // way until someone installs the binary.
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, SECONDARY),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
+ /**
+ * Ghostscript reached a page it could not draw, which its output names.
+ *
+ * <p>Only the recognised page-drawing failure belongs here. E051 is the bucket {@code
+ * ExceptionUtils.analyzeGhostscriptOutput} falls back to for output it does not recognise, so
+ * it also carries killed processes and full disks, which a retry does clear.
+ */
+ STEP_CANNOT_RENDER_PAGE(
+ FailureStage.INTERNAL,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_FILE_FIX,
+ FailureScope.FILE,
+ errorCodes("E054"),
+ fallback(
+ "A page in this document could not be drawn, so the pipeline could not finish."),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(OPEN_IN_TOOL, OWNER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
UNKNOWN(
FailureStage.INTERNAL,
FailureSeverity.ERROR,
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
index a5dd6e8e08..7af0325764 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
@@ -795,10 +795,14 @@ public class PolicyController {
* Only for a single-document run: an incident holds one file reference, so naming one of
* several would attribute the failure to whichever bound first. Counted off resolved inputs,
* not parts.
+ *
+ * <p>Refused for several, not for none. An empty upload resolves to no input at all, and
+ * dropping the reference there filed its failure against no document, which is the one thing
+ * the bell will not show: a caller that named one file named it whether or not it had bytes.
*/
private static String documentReferenceFor(PolicyRunFiles files, PolicyInputs inputs) {
String fileId = files.getFileId();
- if (fileId == null || fileId.isBlank() || inputs.primary().size() != 1) {
+ if (fileId == null || fileId.isBlank() || inputs.primary().size() > 1) {
return null;
}
return fileId;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
index 36f84a06d3..3dc42a4158 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
@@ -24,6 +24,7 @@ import stirling.software.common.service.AutomationRunContext;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
+import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.ZipExtractionUtils;
import stirling.software.proprietary.policy.model.PipelineDefinition;
@@ -299,16 +300,11 @@ public class PolicyExecutor {
}
for (Resource file : files) {
if (!matchesType(file, accepted)) {
- // Reports the extension rather than the filename, since this message becomes the
- // run's error and is persisted on the failure record.
- throw new IOException(
- "Step "
- + operation
- + " accepts "
- + accepted
- + " but received a '"
- + extensionOf(file)
- + "' file");
+ // Coded rather than a bare IOException: this check runs before the step, so the
+ // reader that would have reported the type is never reached and this is the only
+ // place that knows the failure is a type mismatch at all.
+ throw ExceptionUtils.createStepInputTypeException(
+ operation, accepted, extensionOf(file));
}
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureClassifierTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureClassifierTest.java
index 7146f87eab..7e43161632 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureClassifierTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureClassifierTest.java
@@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThatCode;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
+import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
@@ -79,12 +80,46 @@ class FailureClassifierTest {
@Test
void withAnUnclaimedErrorCodeFallsBackToUnknown() {
- // E005 (no pages) is a real code that no kind has adopted yet. It must land in
- // UNKNOWN rather than being force-fitted to the nearest kind.
- assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E005")))
+ // E031 (a step failed on the file, with nothing more specific to say) is a real code
+ // that no kind has adopted. It must land in UNKNOWN rather than being force-fitted to
+ // the nearest kind.
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E031")))
.isEqualTo(FailureKind.UNKNOWN);
}
+ @Test
+ void withACodeForAFileNoOneCanFixClassifiesToItsKind() {
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E006")))
+ .isEqualTo(FailureKind.INPUT_WRONG_TYPE);
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E005")))
+ .isEqualTo(FailureKind.INPUT_EMPTY);
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E010")))
+ .isEqualTo(FailureKind.INPUT_UNREADABLE);
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E030")))
+ .isEqualTo(FailureKind.INPUT_UNAVAILABLE);
+ assertThat(classifier.classify(problemDetail(HttpStatus.SERVICE_UNAVAILABLE, "E063")))
+ .isEqualTo(FailureKind.TOOL_NOT_INSTALLED);
+ assertThat(classifier.classify(problemDetail(HttpStatus.INTERNAL_SERVER_ERROR, "E054")))
+ .isEqualTo(FailureKind.STEP_CANNOT_RENDER_PAGE);
+ }
+
+ @Test
+ void aStepRefusingItsInputTypeIsAWrongTypeNotAnUnknown() {
+ // The engine refuses on extension before the step runs, so the reader that would have
+ // named the type is never reached and this is the only account of what went wrong.
+ ExceptionUtils.StepInputTypeException e =
+ ExceptionUtils.createStepInputTypeException(
+ "/api/v1/security/auto-redact", List.of("pdf"), "cbr");
+ assertThat(classifier.classify(e)).isEqualTo(FailureKind.INPUT_WRONG_TYPE);
+ assertThat(e.getMessage()).contains("pdf").contains("cbr");
+ }
+
+ @Test
+ void anEmptyUploadIsAnEmptyFileNotAnUnknown() {
+ assertThat(classifier.classify(ExceptionUtils.createFileNullOrEmptyException()))
+ .isEqualTo(FailureKind.INPUT_EMPTY);
+ }
+
@Test
void withANonJsonBodyFallsBackToUnknownWithoutThrowing() {
assertThat(classifier.classify(rawBody("Internal Server Error")))
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
index 8681adebd9..f1352d328d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
@@ -341,10 +341,21 @@ class FailureKindTest {
@Test
void byErrorCodeIsEmptyForACodeNoKindHasAdoptedYet() {
- // E005 is PDF_NO_PAGES: a real error code, deliberately not yet a kind.
- assertThat(FailureKind.byErrorCode("E005")).isEmpty();
+ // E031 is FILE_PROCESSING, the catch-all a step throws when it has nothing more
+ // specific to say. It stays unclaimed on purpose: UNKNOWN describes it accurately and
+ // leads with a retry, which is the right offer for a failure nobody can characterise.
+ assertThat(FailureKind.byErrorCode("E031")).isEmpty();
assertThat(FailureKind.byErrorCode(null)).isEmpty();
}
+
+ @Test
+ void aCodeARetryCouldClearIsLeftToUnknown() {
+ // E051 is the bucket analyzeGhostscriptOutput falls back to for output it cannot
+ // recognise, so it also carries killed processes and full disks; E053 is an outright
+ // interruption. Claiming either would tell an owner a rerunnable failure is permanent.
+ assertThat(FailureKind.byErrorCode("E051")).isEmpty();
+ assertThat(FailureKind.byErrorCode("E053")).isEmpty();
+ }
}
@Nested
@@ -380,6 +391,60 @@ class FailureKindTest {
.contains(offered(FailureActionId.OPEN_IN_TOOL, OWNER, OVERFLOW, "openInTool"));
}
+ @Test
+ void aKindWithNothingToOfferDeclaresNoResolutionRatherThanAWeakOne() {
+ // Zero resolutions is legal, so nothing else would notice one of these quietly
+ // gaining a button. Each is here because no action the client can run would change
+ // the outcome: the file is the wrong type, empty, gone, or the server is missing a
+ // binary. A retry belongs to UNKNOWN, which says plainly that we do not know.
+ assertThat(
+ Stream.of(FailureKind.values())
+ .filter(
+ kind ->
+ kind.getOfferedActions().stream()
+ .noneMatch(
+ offer ->
+ offer.slot()
+ == RESOLUTION))
+ .toList())
+ .containsExactlyInAnyOrder(
+ FailureKind.COMPLIANCE_NOT_MET,
+ FailureKind.INPUT_UNREPAIRABLE,
+ FailureKind.INPUT_WRONG_TYPE,
+ FailureKind.INPUT_UNREADABLE,
+ FailureKind.INPUT_EMPTY,
+ FailureKind.INPUT_UNAVAILABLE,
+ FailureKind.TOOL_NOT_INSTALLED,
+ FailureKind.STEP_CANNOT_RENDER_PAGE,
+ FailureKind.UNKNOWN);
+ }
+
+ @Test
+ void aMissingDocumentOffersNothingThatWouldOpenIt() {
+ assertThat(FailureKind.INPUT_UNAVAILABLE.getOfferedActions())
+ .containsExactly(
+ offered(
+ FailureActionId.VIEW_IN_PROCESSOR,
+ TEAM_REVIEWER,
+ OVERFLOW,
+ "viewInProcessor"),
+ offered(FailureActionId.DISMISS, ANYONE_WHO_SEES, OVERFLOW, "dismiss"));
+ }
+
+ @Test
+ void aMissingBinaryIsARunnersProblemNotTheOwners() {
+ // No owner-facing offer at all: the document is fine and a retry fails identically
+ // until someone installs the binary, so the only useful reader is whoever triages.
+ assertThat(FailureKind.TOOL_NOT_INSTALLED.getOfferedActions())
+ .containsExactly(
+ offered(
+ FailureActionId.VIEW_IN_PROCESSOR,
+ TEAM_REVIEWER,
+ SECONDARY,
+ "viewInProcessor"),
+ offered(FailureActionId.DISMISS, ANYONE_WHO_SEES, OVERFLOW, "dismiss"));
+ }
+
@Test
void noKindOffersAcknowledgeAnyMore() {
// Kept in the vocabulary for rows already ACKNOWLEDGED; offered by nothing, so
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
index 872839c640..7b5f3abf6b 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
@@ -931,6 +931,22 @@ class PolicyControllerTest {
assertThat(documentReferenceOf(filesWith("editor-file-1", 3))).isNull();
}
+ @Test
+ @DisplayName("keeps the reference when the one document sent was empty")
+ void keepsTheReferenceForAnEmptyUpload() throws Exception {
+ // An empty part resolves to no input at all, so this once fell to the several-documents
+ // guard and filed the failure against no document. The bell lists only rows naming one,
+ // so the row a reader could see least of became the row they were not shown.
+ PolicyRunFiles files = new PolicyRunFiles();
+ files.setFileId("editor-file-1");
+ files.setFileInput(
+ List.of(
+ new MockMultipartFile(
+ "fileInput", "empty.pdf", "application/pdf", new byte[0])));
+
+ assertThat(documentReferenceOf(files)).isEqualTo("editor-file-1");
+ }
+
@Test
@DisplayName("records nothing when the caller sent no id")
void toleratesACallerThatSendsNoReference() throws Exception {
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 64b81f2865..d4e89c6ec3 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -8423,10 +8423,38 @@ title = "Compliance standard not met"
description = "Your file is damaged, so the run could not read it."
title = "Damaged document"
+[portal.failures.kind.inputEmpty]
+description = "Your file has no content in it, so there was nothing for the run to work on."
+title = "Empty file"
+
[portal.failures.kind.inputPasswordProtected]
description = "Your file is password protected, so the run could not read it."
title = "Password-protected document"
+[portal.failures.kind.inputUnavailable]
+description = "The file behind this run could not be reached, so it was never processed."
+title = "File unavailable"
+
+[portal.failures.kind.inputUnreadable]
+description = "Your file could not be opened, so the run could not read it."
+title = "Unreadable file"
+
+[portal.failures.kind.inputUnrepairable]
+description = "Your file is damaged beyond what the repair tools can fix."
+title = "File could not be repaired"
+
+[portal.failures.kind.inputWrongType]
+description = "Your file is not a format this step can open, so the run could not read it."
+title = "Wrong file type"
+
+[portal.failures.kind.stepCannotRenderPage]
+description = "A page in your file could not be drawn, so the run could not finish."
+title = "Page could not be rendered"
+
+[portal.failures.kind.toolNotInstalled]
+description = "This server is missing software the step needs, so the run could not start it."
+title = "Software not installed"
+
[portal.failures.kind.unknown]
description = "Something went wrong that Stirling does not recognise yet."
title = "Unrecognised issue"
diff --git a/frontend/editor/src/core/services/failureReporting.ts b/frontend/editor/src/core/services/failureReporting.ts
index 52f2aa891f..e148b8a8ea 100644
--- a/frontend/editor/src/core/services/failureReporting.ts
+++ b/frontend/editor/src/core/services/failureReporting.ts
@@ -64,6 +64,32 @@ function isBlobLike(value: unknown): value is { text: () => Promise<string> } {
);
}
+/**
+ * Report a failure whose code and wording are already known, for a client that has learned
+ * something new about a document it already reported. Folds on by the server's own dedup.
+ */
+export async function reportKnownFailure(report: {
+ operation: string;
+ errorCode: string;
+ detail: string | null;
+ fileIds?: string[];
+}): Promise<void> {
+ try {
+ await apiClient.post(
+ REPORT_PATH,
+ {
+ operation: report.operation,
+ errorCode: report.errorCode,
+ fileIds: report.fileIds ?? [],
+ detail: report.detail,
+ },
+ { suppressErrorToast: true },
+ );
+ } catch {
+ // Best-effort, as above: the reader already has the refusal on screen.
+ }
+}
+
export async function reportToolFailure({
operation,
error,
diff --git a/frontend/editor/src/core/services/notificationRetry.test.ts b/frontend/editor/src/core/services/notificationRetry.test.ts
index 29e3b898cd..4e05588d41 100644
--- a/frontend/editor/src/core/services/notificationRetry.test.ts
+++ b/frontend/editor/src/core/services/notificationRetry.test.ts
@@ -420,6 +420,31 @@ describe("unlockLocalDocument", () => {
expect(post).not.toHaveBeenCalled();
});
+ it("reads the reason out of a blob body, rather than showing the transport's words", async () => {
+ // An error body arrives as a blob here too. Left unread, a document nothing can repair
+ // reported only "Request failed with status code 500".
+ getStirlingFiles.mockResolvedValue([new File(["%PDF-1.7"], "broken.pdf")]);
+ post.mockRejectedValue({
+ response: {
+ data: new Blob([
+ JSON.stringify({
+ detail:
+ "This document is damaged in a way the repair tools cannot fix.",
+ errorCode: "E076",
+ }),
+ ]),
+ },
+ message: "Request failed with status code 500",
+ });
+
+ const result = await repairDocuments(["f-1"]);
+
+ expect(result.ok).toBe(false);
+ expect(result.message).toBe(
+ "This document is damaged in a way the repair tools cannot fix.",
+ );
+ });
+
it("returns the server's own message when the password is wrong", async () => {
getStirlingFiles.mockResolvedValue([new File(["%PDF-1.7"], "locked.pdf")]);
post.mockRejectedValue({
@@ -493,7 +518,8 @@ describe("stashMatchesKind", () => {
});
it("gives an unclaimed code to UNKNOWN, and a claimed one never", async () => {
- expect(stashMatchesKind("UNKNOWN", payload({ errorCode: "E005" }))).toBe(
+ // E031 is the step's catch-all, left unclaimed because nothing more specific is known.
+ expect(stashMatchesKind("UNKNOWN", payload({ errorCode: "E031" }))).toBe(
true,
);
expect(stashMatchesKind("UNKNOWN", payload({ errorCode: null }))).toBe(
@@ -504,6 +530,17 @@ describe("stashMatchesKind", () => {
);
});
+ it("matches a kind with no resolution, so its stash is not offered to UNKNOWN", async () => {
+ // These kinds run nothing, but the stash still decides which row a file's failure belongs
+ // to, so a wrong-type failure must not read as the unrecognised one.
+ expect(
+ stashMatchesKind("INPUT_WRONG_TYPE", payload({ errorCode: "E061" })),
+ ).toBe(true);
+ expect(stashMatchesKind("UNKNOWN", payload({ errorCode: "E061" }))).toBe(
+ false,
+ );
+ });
+
it("refuses a kind that claims codes when the stash recorded none", async () => {
expect(
stashMatchesKind("INPUT_CORRUPTED", payload({ errorCode: null })),
diff --git a/frontend/editor/src/core/services/notificationRetry.ts b/frontend/editor/src/core/services/notificationRetry.ts
index f971636d7a..198390f10c 100644
--- a/frontend/editor/src/core/services/notificationRetry.ts
+++ b/frontend/editor/src/core/services/notificationRetry.ts
@@ -48,12 +48,25 @@ export interface RetryPayload {
export const KIND_ERROR_CODES: Record<string, readonly string[]> = {
INPUT_PASSWORD_PROTECTED: ["E004"],
INPUT_CORRUPTED: ["E001", "E002", "E003"],
+ INPUT_UNREPAIRABLE: ["E076"],
COMPLIANCE_NOT_MET: ["E074"],
+ INPUT_WRONG_TYPE: ["E006", "E014", "E018", "E061", "E075"],
+ INPUT_UNREADABLE: ["E010", "E015", "E021", "E034"],
+ INPUT_EMPTY: ["E005", "E012", "E016", "E020", "E032"],
+ INPUT_UNAVAILABLE: ["E030", "E033"],
+ TOOL_NOT_INSTALLED: ["E042", "E062", "E063", "E080"],
+ STEP_CANNOT_RENDER_PAGE: ["E054"],
};
/** Every code any kind claims, so an unclaimed one can be recognised as belonging to UNKNOWN. */
const CLAIMED_CODES = new Set(Object.values(KIND_ERROR_CODES).flat());
+/** Whether `kindId` is the kind `errorCode` belongs to, so a caller can spot a changed verdict. */
+export function kindClaims(kindId: string, errorCode: string): boolean {
+ const claimed = KIND_ERROR_CODES[kindId];
+ return claimed ? claimed.includes(errorCode) : !CLAIMED_CODES.has(errorCode);
+}
+
/** Whether the one stash a file carries is the failure this row describes. */
export function stashMatchesKind(
kindId: string,
@@ -188,6 +201,8 @@ export interface RetryOutcome {
ok: boolean;
reason?: RetryFailure;
message?: string | null;
+ /** The server's code for the refusal, so a caller can tell a permanent one from a retryable. */
+ errorCode?: string | null;
files?: RetryOutputFile[];
}
@@ -246,6 +261,8 @@ export interface RepairOutcome {
ok: boolean;
reason?: RetryFailure;
message?: string | null;
+ /** The server's code for the refusal, so a caller can tell a permanent one from a retryable. */
+ errorCode?: string | null;
repaired?: RepairedDocument[];
}
@@ -267,7 +284,12 @@ export async function repairDocuments(
for (const fileId of usable) {
const outcome = await postDocuments(REPAIR_ENDPOINT, {}, [fileId], null);
if (!outcome.ok) {
- return { ok: false, reason: outcome.reason, message: outcome.message };
+ return {
+ ok: false,
+ reason: outcome.reason,
+ message: outcome.message,
+ errorCode: outcome.errorCode,
+ };
}
const file = outcome.files?.[0];
if (!file) return { ok: false, reason: "notRetryable", message: null };
@@ -334,7 +356,8 @@ async function postFiles(
),
};
} catch (error) {
- return { ok: false, reason: "serverMessage", message: messageOf(error) };
+ const said = await serverFailureOf(error);
+ return { ok: false, reason: "serverMessage", ...said };
}
}
@@ -446,13 +469,60 @@ function prunedBelow(value: unknown, depth: number): unknown {
return kept;
}
-/** What the server said, or null when it said nothing usable. Never carries the password. */
-function messageOf(error: unknown): string | null {
- const response = (error as { response?: { data?: unknown } })?.response?.data;
- if (typeof response === "string" && response.trim() !== "") return response;
+/**
+ * What the server said and why, or nulls when it said nothing usable. Never carries the password.
+ * These calls ask for a blob, so an error body arrives as one and has to be read to be understood.
+ */
+async function serverFailureOf(
+ error: unknown,
+): Promise<{ message: string | null; errorCode: string | null }> {
+ const body = (error as { response?: { data?: unknown } })?.response?.data;
+
+ const text = body instanceof Blob ? await textOf(body) : body;
+ if (typeof text === "string" && text.trim() !== "") {
+ return { message: detailOf(text) ?? text, errorCode: errorCodeOf(text) };
+ }
const message = (error as { message?: unknown })?.message;
- return typeof message === "string" && message.trim() !== "" ? message : null;
+ return {
+ message:
+ typeof message === "string" && message.trim() !== "" ? message : null,
+ errorCode: null,
+ };
+}
+
+/** Via FileReader, which jsdom implements and `Blob.text` it does not. Null rather than throwing. */
+function textOf(blob: Blob): Promise<string | null> {
+ return new Promise((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result));
+ reader.onerror = () => resolve(null);
+ reader.readAsText(blob);
+ });
+}
+
+/**
+ * What a JSON error body says, or null when the text is not one. Two shapes reach here: Problem
+ * Details from a handler, and `{"error": ...}` from a job that failed.
+ */
+function detailOf(text: string): string | null {
+ try {
+ const body = JSON.parse(text) as { detail?: unknown; error?: unknown };
+ const said = typeof body.detail === "string" ? body.detail : body.error;
+ return typeof said === "string" && said.trim() !== "" ? said : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The error code a JSON body carries, for a caller deciding what the row may still offer. */
+function errorCodeOf(text: string): string | null {
+ try {
+ const code = (JSON.parse(text) as { errorCode?: unknown }).errorCode;
+ return typeof code === "string" && code.trim() !== "" ? code : null;
+ } catch {
+ return null;
+ }
}
async function writeRecords(records: StoredRetryRecord[]): Promise<void> {
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/repair.test.tsx b/frontend/editor/src/proprietary/components/notifications/resolutions/repair.test.tsx
index 08f1c929a6..fd90209006 100644
--- a/frontend/editor/src/proprietary/components/notifications/resolutions/repair.test.tsx
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/repair.test.tsx
@@ -36,6 +36,11 @@ vi.mock("@app/services/notificationPolicyRetry", () => ({
}));
const reportNotificationResolved = vi.fn();
+const reportKnownFailure = vi.fn();
+vi.mock("@app/services/failureReporting", () => ({
+ reportKnownFailure: (...args: unknown[]) => reportKnownFailure(...args),
+}));
+
vi.mock("@app/services/notifications", async () => ({
...(await vi.importActual<typeof import("@app/services/notifications")>(
"@app/services/notifications",
@@ -192,6 +197,7 @@ beforeEach(() => {
});
// Placeable by default: the browser still holds the policy the failure names.
canPlacePolicy.mockReset().mockReturnValue(true);
+ reportKnownFailure.mockReset().mockResolvedValue(undefined);
window.sessionStorage.clear();
window.history.pushState({}, "", "/");
});
@@ -226,6 +232,46 @@ describe("REPAIR", () => {
expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
});
+ it("replaces the row when the repair tools refuse the document", async () => {
+ // The row offered a fix that has now been refused, so leaving it as damaged would keep
+ // offering it. The new code names a kind with no Repair, and the old row is closed behind it.
+ repairDocuments.mockResolvedValue({
+ ok: false,
+ reason: "serverMessage",
+ message: "This document is damaged in a way the repair tools cannot fix.",
+ errorCode: "E076",
+ });
+
+ const outcome = await registry().REPAIR?.run(
+ context({ kindId: "INPUT_CORRUPTED" }),
+ );
+
+ expect(outcome).toEqual({
+ ok: false,
+ message: "This document is damaged in a way the repair tools cannot fix.",
+ });
+ expect(reportKnownFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ errorCode: "E076", fileIds: ["f-1"] }),
+ );
+ expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1");
+ });
+
+ it("leaves the row alone when the refusal is what its kind already says", async () => {
+ // A code the row's own kind claims tells the reader nothing new, so swapping the row would
+ // close and reopen it for no change.
+ repairDocuments.mockResolvedValue({
+ ok: false,
+ reason: "serverMessage",
+ message: "still damaged",
+ errorCode: "E001",
+ });
+
+ await registry().REPAIR?.run(context({ kindId: "INPUT_CORRUPTED" }));
+
+ expect(reportKnownFailure).not.toHaveBeenCalled();
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
it("re-runs the stashed operation over the repaired bytes, not the original", async () => {
const outcome = await registry().REPAIR?.run(
context({ kindId: "INPUT_CORRUPTED" }),
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/resolution.ts b/frontend/editor/src/proprietary/components/notifications/resolutions/resolution.ts
index de8f15bbc2..69258fe8dc 100644
--- a/frontend/editor/src/proprietary/components/notifications/resolutions/resolution.ts
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/resolution.ts
@@ -7,6 +7,7 @@ import type {
import { fileStorage } from "@app/services/fileStorage";
import {
clearRetryPayload,
+ kindClaims,
stashMatchesKind,
type RetryFailure,
type RetryOutcome,
@@ -19,6 +20,7 @@ import {
type PolicyRerunOutcome,
type PolicyRetryTarget,
} from "@app/services/notificationPolicyRetry";
+import { reportKnownFailure } from "@app/services/failureReporting";
import { reportNotificationResolved } from "@app/services/notifications";
import type { FileId } from "@app/types/file";
import type { StirlingFileStub } from "@app/types/fileContext";
@@ -57,6 +59,8 @@ export interface ProduceOutcome {
ok: boolean;
reason?: RetryFailure;
message?: string | null;
+ /** The server's code for a refusal, so a verdict that outlives this row can replace it. */
+ errorCode?: string | null;
produced?: ProducedDocument[];
}
@@ -232,6 +236,29 @@ export function rerunOutcome(
};
}
+/**
+ * Replace the row when a refusal says something its kind does not, so a fix that has just been
+ * declined is not offered again. A code the kind already claims changes nothing and is left.
+ */
+async function supersede(
+ context: NotificationActionContext,
+ outcome: ProduceOutcome,
+): Promise<void> {
+ const errorCode = outcome.errorCode;
+ if (!errorCode || kindClaims(context.notification.kindId, errorCode)) return;
+
+ const toolId = toolOf(
+ context.retryPayload ?? ({ operation: "" } as RetryPayload),
+ );
+ await reportKnownFailure({
+ operation: toolId ?? context.notification.kindId,
+ errorCode,
+ detail: outcome.message ?? null,
+ fileIds: context.notification.fileId ? [context.notification.fileId] : [],
+ });
+ await reportNotificationResolved(context.notification.id);
+}
+
/** Storage too, or a file merely closed in the sidebar gets a copy rather than a version. */
async function parentStubFor(
fileStore: ContextType<typeof FileStoreContext>,
@@ -282,7 +309,10 @@ export function resolutionSpec(
}
const outcome = await resolution.produce(target, context, password);
- if (!outcome.ok) return retryFailure(t, outcome);
+ if (!outcome.ok) {
+ await supersede(context, outcome);
+ return retryFailure(t, outcome);
+ }
const produced = outcome.produced ?? [];
if (target.kind === "policy") {
diff --git a/testing/failure-kind-codes.json b/testing/failure-kind-codes.json
index dfd8e41f78..b2b24e6dc9 100644
--- a/testing/failure-kind-codes.json
+++ b/testing/failure-kind-codes.json
@@ -9,6 +9,13 @@
"kinds": {
"INPUT_PASSWORD_PROTECTED": ["E004"],
"INPUT_CORRUPTED": ["E001", "E002", "E003"],
- "COMPLIANCE_NOT_MET": ["E074"]
+ "INPUT_UNREPAIRABLE": ["E076"],
+ "COMPLIANCE_NOT_MET": ["E074"],
+ "INPUT_WRONG_TYPE": ["E006", "E014", "E018", "E061", "E075"],
+ "INPUT_UNREADABLE": ["E010", "E015", "E021", "E034"],
+ "INPUT_EMPTY": ["E005", "E012", "E016", "E020", "E032"],
+ "INPUT_UNAVAILABLE": ["E030", "E033"],
+ "TOOL_NOT_INSTALLED": ["E042", "E062", "E063", "E080"],
+ "STEP_CANNOT_RENDER_PAGE": ["E054"]
}
}