Skip to content

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

Recognise damaged documents and offer to repair them (#7927)

EthanHealy0133a6aab98bdc
diff --git a/app/proprietary/build.gradle b/app/proprietary/build.gradle
index c2fe10b42e..8a261aa8be 100644
--- a/app/proprietary/build.gradle
+++ b/app/proprietary/build.gradle
@@ -120,3 +120,14 @@ tasks.register('type3SignatureTool', JavaExec) {
mainClass = 'stirling.software.SPDF.service.pdfjson.type3.tool.Type3SignatureTool'
standardInput = System.in
}
+
+// FailureKindTest asserts the enum against two files outside this project, found by walking up to
+// the repo root: the kind-to-code fixture the frontend also reads, and the English copy every kind
+// must have a key in. Gradle cannot infer either, so without this the task is up-to-date when only
+// one of them changed and the mismatch surfaces on the next unrelated Java edit instead.
+tasks.named('test', Test).configure {
+ inputs.files(
+ rootProject.file('testing/failure-kind-codes.json'),
+ rootProject.file('frontend/editor/public/locales/en-US/translation.toml')
+ ).withPropertyName('sharedConformanceFixtures').optional()
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java
index a213b97928..2a4a5f4090 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureActionId.java
@@ -22,7 +22,10 @@ public enum FailureActionId {
OPEN_IN_TOOL(Execution.CLIENT, "Retry"),
/** Unlocks the document with a password the owner supplies. */
- DECRYPT(Execution.CLIENT, "Decrypt and retry"),
+ DECRYPT(Execution.CLIENT, "Unlock"),
+
+ /** Repairs the document in the owner's client, then re-runs. */
+ REPAIR(Execution.CLIENT, "Repair"),
/** Open the document behind the incident, in whichever client can resolve its id. */
VIEW_FILE(Execution.CLIENT, "View file"),
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 1d1568fbe5..496fc234b5 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
@@ -3,6 +3,7 @@ package stirling.software.proprietary.failure;
import static stirling.software.proprietary.failure.FailureActionId.DECRYPT;
import static stirling.software.proprietary.failure.FailureActionId.DISMISS;
import static stirling.software.proprietary.failure.FailureActionId.OPEN_IN_TOOL;
+import static stirling.software.proprietary.failure.FailureActionId.REPAIR;
import static stirling.software.proprietary.failure.FailureActionId.VIEW_FILE;
import static stirling.software.proprietary.failure.FailureActionId.VIEW_IN_PROCESSOR;
import static stirling.software.proprietary.failure.FailureActionSlot.OVERFLOW;
@@ -44,6 +45,26 @@ public enum FailureKind {
global(OPEN_IN_TOOL, OWNER, OVERFLOW),
global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+ /**
+ * E003 rides along. PDFBox swallows every decryption failure during lazy dereference, so it is
+ * not expected to render; claiming it only guarantees a known code never lands on {@link
+ * #UNKNOWN} if that ever changes.
+ */
+ INPUT_CORRUPTED(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_FILE_FIX,
+ FailureScope.FILE,
+ errorCodes("E001", "E002", "E003"),
+ fallback("This document is damaged, so the pipeline could not read it."),
+ // Opening the tool is offered but not promoted: the same bytes fail the same way, so
+ // it only helps when the upload itself truncated them.
+ resolution(REPAIR, OWNER),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(OPEN_IN_TOOL, OWNER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
COMPLIANCE_NOT_MET(
FailureStage.BLOCKED,
FailureSeverity.ERROR,
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 951b11c056..7146f87eab 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
@@ -67,11 +67,21 @@ class FailureClassifierTest {
.isEqualTo(FailureKind.INPUT_PASSWORD_PROTECTED);
}
+ @Test
+ void everyUnreadableDocumentIsTheSameKind() {
+ // E003 included on purpose: a known code must classify, never fall to UNKNOWN.
+ for (String code : new String[] {"E001", "E002", "E003"}) {
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, code)))
+ .as("%s", code)
+ .isEqualTo(FailureKind.INPUT_CORRUPTED);
+ }
+ }
+
@Test
void withAnUnclaimedErrorCodeFallsBackToUnknown() {
- // E001 (corrupted PDF) is a real code that no kind has adopted yet. It must land in
+ // 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, "E001")))
+ assertThat(classifier.classify(problemDetail(HttpStatus.BAD_REQUEST, "E005")))
.isEqualTo(FailureKind.UNKNOWN);
}
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 939f9308a0..8681adebd9 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
@@ -15,7 +15,9 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -28,6 +30,10 @@ import org.junit.jupiter.params.provider.EnumSource;
import stirling.software.common.util.ExceptionUtils;
+import tools.jackson.core.JacksonException;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
/**
* Tests for {@link FailureKind}. Mostly invariants over the whole enum rather than assertions about
* individual members, so a kind added later cannot be malformed in a way that only shows up as a
@@ -35,6 +41,18 @@ import stirling.software.common.util.ExceptionUtils;
*/
class FailureKindTest {
+ /** Located by walking up, so a test does not depend on the directory Gradle runs it in. */
+ private static Path repoFile(String relative) {
+ for (Path dir = Path.of("").toAbsolutePath(); dir != null; dir = dir.getParent()) {
+ Path candidate = dir.resolve(relative);
+ if (Files.isRegularFile(candidate)) {
+ return candidate;
+ }
+ }
+ throw new IllegalStateException(
+ "No " + relative + " above " + Path.of("").toAbsolutePath());
+ }
+
/** In full, so a declaration pairing the right action with the wrong audience cannot pass. */
private static FailureKind.OfferedAction offered(
FailureActionId id,
@@ -206,21 +224,13 @@ class FailureKindTest {
}
private static List<String> readTranslations() {
- // Located by walking up, so the test does not depend on the directory Gradle runs it
- // in.
- Path relative = Path.of("frontend/editor/public/locales/en-US/translation.toml");
- for (Path dir = Path.of("").toAbsolutePath(); dir != null; dir = dir.getParent()) {
- Path candidate = dir.resolve(relative);
- if (Files.isRegularFile(candidate)) {
- try {
- return Files.readAllLines(candidate, StandardCharsets.UTF_8);
- } catch (IOException e) {
- throw new UncheckedIOException(e);
- }
- }
+ try {
+ return Files.readAllLines(
+ repoFile("frontend/editor/public/locales/en-US/translation.toml"),
+ StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
}
- throw new IllegalStateException(
- "No " + relative + " above " + Path.of("").toAbsolutePath());
}
}
@@ -272,22 +282,67 @@ class FailureKindTest {
void byErrorCodeResolvesTheClaimingKind() {
assertThat(FailureKind.byErrorCode("E004"))
.contains(FailureKind.INPUT_PASSWORD_PROTECTED);
+ assertThat(FailureKind.byErrorCode("E001")).contains(FailureKind.INPUT_CORRUPTED);
+ assertThat(FailureKind.byErrorCode("E002")).contains(FailureKind.INPUT_CORRUPTED);
}
@Test
- void everyCodeAKindClaimsIsPinned() {
+ void aBrokenEncryptionIsNotAMissingPassword() {
+ // E003 is reached only once the key was accepted, so no password would help.
+ assertThat(FailureKind.byErrorCode("E003")).contains(FailureKind.INPUT_CORRUPTED);
+ assertThat(FailureKind.INPUT_CORRUPTED.declares(FailureActionId.DECRYPT)).isFalse();
+ }
+
+ @Test
+ void everyCodeAKindClaimsMatchesTheSharedFixture() {
// The bell mirrors these in KIND_ERROR_CODES (notificationRetry.ts) to tell one file's
- // stashed failure from another's. Adding a code here without adding it there makes a
- // retry match the wrong incident, so this fails until both move together.
- assertThat(FailureKind.INPUT_PASSWORD_PROTECTED.getErrorCodes())
- .containsExactly("E004");
- assertThat(FailureKind.UNKNOWN.getErrorCodes()).isEmpty();
+ // stashed failure from another's, and a Java test cannot read a TypeScript file. Both
+ // sides assert against testing/failure-kind-codes.json instead, so a code added to one
+ // and not the other fails on whichever side was not updated.
+ assertThat(claimedErrorCodes()).isEqualTo(sharedFixtureCodes());
+ }
+
+ /** Kinds claiming nothing are left out, matching what the fixture records. */
+ private static Map<String, List<String>> claimedErrorCodes() {
+ return Stream.of(FailureKind.values())
+ .filter(kind -> !kind.getErrorCodes().isEmpty())
+ .collect(
+ Collectors.toMap(
+ FailureKind::getId,
+ FailureKind::getErrorCodes,
+ (first, second) -> first,
+ LinkedHashMap::new));
+ }
+
+ private static Map<String, List<String>> sharedFixtureCodes() {
+ JsonNode kinds;
+ try {
+ kinds =
+ JsonMapper.builder()
+ .build()
+ .readTree(repoFile("testing/failure-kind-codes.json").toFile())
+ .get("kinds");
+ } catch (JacksonException e) {
+ throw new IllegalStateException("testing/failure-kind-codes.json is not JSON", e);
+ }
+
+ Map<String, List<String>> codes = new LinkedHashMap<>();
+ kinds.propertyStream()
+ .forEach(
+ entry ->
+ codes.put(
+ entry.getKey(),
+ entry.getValue()
+ .valueStream()
+ .map(JsonNode::asString)
+ .toList()));
+ return codes;
}
@Test
void byErrorCodeIsEmptyForACodeNoKindHasAdoptedYet() {
- // E001 is PDF_CORRUPTED: a real error code, deliberately not yet a kind.
- assertThat(FailureKind.byErrorCode("E001")).isEmpty();
+ // E005 is PDF_NO_PAGES: a real error code, deliberately not yet a kind.
+ assertThat(FailureKind.byErrorCode("E005")).isEmpty();
assertThat(FailureKind.byErrorCode(null)).isEmpty();
}
}
@@ -318,6 +373,13 @@ class FailureKindTest {
offered(FailureActionId.DISMISS, ANYONE_WHO_SEES, OVERFLOW, "dismiss"));
}
+ @Test
+ void aRepairableKindNeverPromotesOpenInToolOverTheRepair() {
+ assertThat(FailureKind.INPUT_CORRUPTED.getOfferedActions())
+ .contains(offered(FailureActionId.REPAIR, OWNER, RESOLUTION, "repair"))
+ .contains(offered(FailureActionId.OPEN_IN_TOOL, OWNER, OVERFLOW, "openInTool"));
+ }
+
@Test
void noKindOffersAcknowledgeAnyMore() {
// Kept in the vocabulary for rows already ACKNOWLEDGED; offered by nothing, so
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index d637932c97..72a08aa858 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -5752,6 +5752,10 @@ noDocumentLinked = "This failure is not linked to a specific document, so it can
notOnThisDevice = "This document is not on this device, so it cannot be opened or retried here."
occurrences = "{{count}} times"
open = "Notifications"
+repairAdoptFailed = "The document was repaired but could not be opened here. Try the Repair tool directly."
+repairedNotRerun = "The document was repaired and opened here, but the policy could not be run on it again."
+repairedRerunNotAdopted = "The repaired document went through, but its result could not be opened here."
+repairedRerunUndelivered = "The document was repaired and the policy re-run started, but its result cannot be delivered here, so this failure stays open."
rerunRejected = "The policy could not be run again just now. Try again in a moment."
rerunUndelivered = "The policy re-run started, but its result cannot be delivered here, so this failure stays open."
retryUnavailable = "This document can no longer be retried from this browser."
@@ -8194,9 +8198,10 @@ searchPlaceholder = "Search issues, users and errors"
[portal.failures.action]
acknowledge = "Acknowledge"
-decrypt = "Decrypt and retry"
+decrypt = "Unlock"
dismiss = "Dismiss"
openInTool = "Retry"
+repair = "Repair"
viewFile = "View file"
viewInProcessor = "View in processor"
@@ -8233,6 +8238,10 @@ user = "User"
description = "The compliance check refused this document because it does not meet the standard the policy validates against. The violation is shown below."
title = "Compliance standard not met"
+[portal.failures.kind.inputCorrupted]
+description = "Your file is damaged, so the run could not read it."
+title = "Damaged document"
+
[portal.failures.kind.inputPasswordProtected]
description = "Your file is password protected, so the run could not read it."
title = "Password-protected document"
diff --git a/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx b/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx
index 2486b1482f..0339a27fde 100644
--- a/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx
+++ b/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx
@@ -378,6 +378,28 @@ describe("NotificationBell", () => {
expect(screen.getByText("Unrecognised failure")).toBeTruthy();
});
+ it("re-reads the list once an action has run, rather than waiting for the next poll", async () => {
+ // A resolution closes its row server-side. The panel polls every 30s, so without a re-read
+ // the row a reader just fixed stays on screen, and reopening the panel does not shift it.
+ const run = vi.fn();
+ h.specs = { REPAIR: { available: () => true, run } };
+ fetchNotifications.mockResolvedValue([
+ notification("a", "Damaged document", { actions: [offer("REPAIR")] }),
+ ]);
+ render(<NotificationBell />);
+ await openPanel();
+
+ // Repaired: the server no longer reports it.
+ fetchNotifications.mockResolvedValue([]);
+ fireEvent.click(
+ screen.getByRole("button", { name: "REPAIR: Damaged document" }),
+ );
+
+ await waitFor(() =>
+ expect(screen.queryByText("Damaged document")).toBeNull(),
+ );
+ });
+
it("closes the panel on its way to a destination behind it", async () => {
const run = vi.fn();
h.specs = { VIEW_FILE: { available: () => true, run, closesPanel: true } };
diff --git a/frontend/editor/src/core/components/notifications/NotificationItem.tsx b/frontend/editor/src/core/components/notifications/NotificationItem.tsx
index 0e102ea3bc..62402f65ff 100644
--- a/frontend/editor/src/core/components/notifications/NotificationItem.tsx
+++ b/frontend/editor/src/core/components/notifications/NotificationItem.tsx
@@ -4,7 +4,10 @@ import { useTranslation } from "react-i18next";
import { Menu, Tooltip } from "@mantine/core";
import { ActionIcon, Button } from "@app/ui";
import LocalIcon from "@app/components/shared/LocalIcon";
-import { isResolvableHere } from "@app/hooks/useNotifications";
+import {
+ isResolvableHere,
+ refreshNotificationsNow,
+} from "@app/hooks/useNotifications";
import type { NotificationDocumentState } from "@app/hooks/useNotifications";
import type {
ClientActionRegistry,
@@ -135,6 +138,10 @@ export function NotificationItem({
return;
}
+ // A resolution closes its row server-side, and the panel reads that list on a 30s poll, so
+ // without this the row a reader just fixed sits there until a poll happens to land. Re-read
+ // rather than patched here, as the password path does: the server decides what closed.
+ refreshNotificationsNow();
if (spec.closesPanel) onDismissPanel();
};
diff --git a/frontend/editor/src/core/constants/toolEndpoints.ts b/frontend/editor/src/core/constants/toolEndpoints.ts
new file mode 100644
index 0000000000..bafebd376e
--- /dev/null
+++ b/frontend/editor/src/core/constants/toolEndpoints.ts
@@ -0,0 +1,9 @@
+import type { ToolEndpoint } from "@app/types/toolApiTypes";
+
+// Shared by the tool hooks and the notification retry service. The service cannot import the
+// hooks that would otherwise define these: useToolOperation imports the service, so it would be
+// a cycle. `satisfies` keeps each checked against the generated routes, so a rename fails here.
+export const REMOVE_PASSWORD_ENDPOINT =
+ "/api/v1/security/remove-password" satisfies ToolEndpoint;
+
+export const REPAIR_ENDPOINT = "/api/v1/misc/repair" satisfies ToolEndpoint;
diff --git a/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts b/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts
index c55040c7f2..635df0da4c 100644
--- a/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts
+++ b/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts
@@ -5,13 +5,10 @@ import {
import {
objectToFormData,
type ToolApiParams,
- type ToolEndpoint,
} from "@app/hooks/tools/shared/toolApiMapping";
+import { REMOVE_PASSWORD_ENDPOINT } from "@app/constants/toolEndpoints";
-// Defined here (not in the operation config) so both the mappers and the config
-// share one endpoint constant without a circular import via FileContext.
-export const REMOVE_PASSWORD_ENDPOINT =
- "/api/v1/security/remove-password" satisfies ToolEndpoint;
+export { REMOVE_PASSWORD_ENDPOINT };
type RemovePasswordApiParams = ToolApiParams[typeof REMOVE_PASSWORD_ENDPOINT];
// Convert the tool's UI parameters into the remove-password request body. The
diff --git a/frontend/editor/src/core/hooks/tools/repair/useRepairOperation.ts b/frontend/editor/src/core/hooks/tools/repair/useRepairOperation.ts
index af05cf59b9..0562ef2833 100644
--- a/frontend/editor/src/core/hooks/tools/repair/useRepairOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/repair/useRepairOperation.ts
@@ -6,15 +6,13 @@ import {
import {
fileOnlyMapping,
objectToFormData,
- type ToolEndpoint,
} from "@app/hooks/tools/shared/toolApiMapping";
import { createStandardErrorHandler } from "@app/utils/toolErrorHandler";
import {
RepairParameters,
defaultParameters,
} from "@app/hooks/tools/repair/useRepairParameters";
-
-const ENDPOINT = "/api/v1/misc/repair" satisfies ToolEndpoint;
+import { REPAIR_ENDPOINT } from "@app/constants/toolEndpoints";
// Repair takes only a file; there are no request parameters to map.
const { toApiParams, fromApiParams } = fileOnlyMapping();
@@ -30,7 +28,7 @@ export const repairOperationConfig = defineSingleFileTool({
toApiParams,
fromApiParams,
operationType: "repair",
- endpoint: ENDPOINT,
+ endpoint: REPAIR_ENDPOINT,
defaultParameters,
});
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
index fddcb49788..13fc7dcecc 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
@@ -167,11 +167,16 @@ export const useToolOperation = <TParams>(
) {
return;
}
+ // The request body, not TParams: buildFormData posts what toApiParams returns, and the two
+ // shapes are free to disagree. A tool with no mapper stashes its UI shape and says so, so
+ // the row keeps its plain retry without anything re-running those parameters unattended.
+ const apiParams = config.toApiParams?.(params);
void errorCodeOf(error).then((errorCode) =>
stashRetryPayload({
operation: config.operationType,
endpoint: runtimeEndpoint,
- params: params as Record<string, unknown>,
+ params: (apiParams ?? params) as Record<string, unknown>,
+ paramsMapped: apiParams !== undefined,
fileIds,
multiFile: config.toolType === ToolType.multiFile,
errorCode,
@@ -179,7 +184,7 @@ export const useToolOperation = <TParams>(
}),
);
},
- [config.operationType, config.toolType, notificationsAvailable],
+ [config, notificationsAvailable],
);
const getCompatibleFiles = useCallback(
diff --git a/frontend/editor/src/core/i18n/translationAudit.ts b/frontend/editor/src/core/i18n/translationAudit.ts
index 44b283ee5f..ba0bff86f8 100644
--- a/frontend/editor/src/core/i18n/translationAudit.ts
+++ b/frontend/editor/src/core/i18n/translationAudit.ts
@@ -114,6 +114,9 @@ export const I18N_PROJECTS: TranslationProject[] = [
// Server-sent keys rendered with t(thatKey), so nothing in source names them.
/^portal\.failures\.disabled\./,
/^portal\.failures\.action\./,
+ // A kind's title and description arrive the same way, derived server-side from the kind
+ // id, so adding a kind adds copy that no source file will ever name.
+ /^portal\.failures\.kind\./,
// Encryption panel copy keyed by backend enum values: key status, write
// state, migration state, and the reason a status read was refused. Each
// is t(`...${value}`) where the value comes from the API response.
diff --git a/frontend/editor/src/core/services/notificationRetry.test.ts b/frontend/editor/src/core/services/notificationRetry.test.ts
index 6241579649..29e3b898cd 100644
--- a/frontend/editor/src/core/services/notificationRetry.test.ts
+++ b/frontend/editor/src/core/services/notificationRetry.test.ts
@@ -1,6 +1,10 @@
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
import { beforeEach, describe, expect, it, vi } from "vitest";
import "fake-indexeddb/auto";
import { indexedDBManager } from "@app/services/indexedDBManager";
+import type { RetryPayload } from "@app/services/notificationRetry";
// The stash survives a reload, cannot grow without bound, and never holds a password.
@@ -20,11 +24,16 @@ vi.mock("@app/services/apiClient", () => ({
}));
const {
+ KIND_ERROR_CODES,
stashRetryPayload,
clearRetryPayload,
loadRetryPayload,
hasLocalFile,
+ repairDocuments,
+ retryInputIds,
+ retryWithFiles,
retryWithPassword,
+ stashMatchesKind,
unlockLocalDocument,
} = await import("@app/services/notificationRetry");
@@ -41,8 +50,15 @@ function payload(overrides: Partial<Record<string, unknown>> = {}) {
multiFile: false,
errorCode: "E004",
recordedAt: 1_000,
+ replayUnfaithful: false,
...overrides,
- } as Parameters<typeof stashRetryPayload>[0];
+ } as RetryPayload;
+}
+
+/** What a tool hands the stash: the request body it posted, plus whether it could map one. */
+function stashable(overrides: Partial<Record<string, unknown>> = {}) {
+ const { replayUnfaithful: _flag, ...rest } = payload(overrides);
+ return { ...rest, paramsMapped: true, ...overrides };
}
/** Reads records straight out of IndexedDB, bypassing the service's own mapping. */
@@ -73,7 +89,7 @@ beforeEach(async () => {
describe("the retry stash", () => {
it("gives back what was stashed, keyed on the file the failure was filed against", async () => {
await stashRetryPayload(
- payload({ params: { onlyPages: "1-3" }, fileIds: ["f-1", "f-2"] }),
+ stashable({ params: { onlyPages: "1-3" }, fileIds: ["f-1", "f-2"] }),
);
await expect(loadRetryPayload("f-1")).resolves.toEqual({
@@ -83,6 +99,7 @@ describe("the retry stash", () => {
fileIds: ["f-1", "f-2"],
multiFile: false,
errorCode: "E004",
+ replayUnfaithful: false,
recordedAt: 1_000,
});
// Every file in the run gets a record, so the bell can retry from any of them.
@@ -92,7 +109,7 @@ describe("the retry stash", () => {
});
it("has nothing for a file it never saw, or for no file at all", async () => {
- await stashRetryPayload(payload());
+ await stashRetryPayload(stashable());
await expect(loadRetryPayload("f-other")).resolves.toBeNull();
await expect(loadRetryPayload(null)).resolves.toBeNull();
@@ -101,10 +118,16 @@ describe("the retry stash", () => {
it("keeps the most recent operation that failed on a file, matching the server's one-incident-per-file dedup", async () => {
await stashRetryPayload(
- payload({ operation: "compress", endpoint: "/api/v1/misc/compress-pdf" }),
+ stashable({
+ operation: "compress",
+ endpoint: "/api/v1/misc/compress-pdf",
+ }),
);
await stashRetryPayload(
- payload({ operation: "rotate", endpoint: "/api/v1/general/rotate-pdf" }),
+ stashable({
+ operation: "rotate",
+ endpoint: "/api/v1/general/rotate-pdf",
+ }),
);
await expect(loadRetryPayload("f-1")).resolves.toMatchObject({
@@ -117,7 +140,9 @@ describe("the retry stash", () => {
it("evicts the oldest once it is full, so it cannot grow for the lifetime of the origin", async () => {
// One past the cap: the first failure stashed is the one that goes.
for (let i = 0; i < 26; i += 1) {
- await stashRetryPayload(payload({ fileIds: [`f-${i}`], recordedAt: i }));
+ await stashRetryPayload(
+ stashable({ fileIds: [`f-${i}`], recordedAt: i }),
+ );
}
expect(await storedRecords()).toHaveLength(25);
@@ -131,7 +156,7 @@ describe("the retry stash", () => {
// One failed multi-file run writes a record per file under one recordedAt, so evicting by
// time alone would keep an arbitrary 25 of them and offer no retry for the rest.
const batch = Array.from({ length: 30 }, (_, i) => `b-${i}`);
- await stashRetryPayload(payload({ fileIds: batch, recordedAt: 100 }));
+ await stashRetryPayload(stashable({ fileIds: batch, recordedAt: 100 }));
expect(await storedRecords()).toHaveLength(30);
for (const fileId of [batch[0], batch[15], batch[29]]) {
@@ -142,10 +167,10 @@ describe("the retry stash", () => {
});
it("evicts earlier failures before the batch that just landed", async () => {
- await stashRetryPayload(payload({ fileIds: ["old"], recordedAt: 1 }));
+ await stashRetryPayload(stashable({ fileIds: ["old"], recordedAt: 1 }));
const batch = Array.from({ length: 25 }, (_, i) => `n-${i}`);
- await stashRetryPayload(payload({ fileIds: batch, recordedAt: 2 }));
+ await stashRetryPayload(stashable({ fileIds: batch, recordedAt: 2 }));
// The row on screen is the new one, so it is the older unrelated stash that goes.
await expect(loadRetryPayload("old")).resolves.toBeNull();
@@ -155,7 +180,7 @@ describe("the retry stash", () => {
});
it("forgets a file's stash once its failure is resolved", async () => {
- await stashRetryPayload(payload({ fileIds: ["f-1", "f-2"] }));
+ await stashRetryPayload(stashable({ fileIds: ["f-1", "f-2"] }));
await clearRetryPayload("f-1");
@@ -168,7 +193,7 @@ describe("the retry stash", () => {
it("stores no password, whichever field the tool submitted it in", async () => {
await stashRetryPayload(
- payload({
+ stashable({
params: {
password: "hunter2",
newOwnerPassword: "hunter2",
@@ -187,10 +212,54 @@ describe("the retry stash", () => {
/pass(word|phrase)|token/i,
);
// The rest survive: without them a retry re-runs a different operation than the one that failed.
- expect((await loadRetryPayload("f-1"))?.params).toEqual({
+ const loaded = await loadRetryPayload("f-1");
+ expect(loaded?.params).toEqual({
nested: { keep: "yes" },
keepThese: ["a", "b"],
});
+ // And the loss is recorded: a re-run without the password is not the run that failed.
+ expect(loaded?.replayUnfaithful).toBe(true);
+ });
+
+ it("marks a stash unfaithful when the tool could not map its request body", async () => {
+ // A tool whose UI settings have no mapping to the API's own names would replay under the
+ // wrong field names, run the server's defaults, and then be reported as the fix. Only the
+ // automatic re-run is withheld; the plain retry still opens the tool with its settings.
+ await stashRetryPayload(
+ stashable({ params: { compressionLevel: "5" }, paramsMapped: false }),
+ );
+
+ expect((await loadRetryPayload("f-1"))?.replayUnfaithful).toBe(true);
+ });
+
+ it("knows when nothing was dropped, so a faithful re-run stays on offer", async () => {
+ await stashRetryPayload(stashable({ params: { level: "5" } }));
+
+ expect((await loadRetryPayload("f-1"))?.replayUnfaithful).toBe(false);
+ });
+
+ it("assumes a record from before the flag dropped something", async () => {
+ // Fail closed: the only cost is an automatic re-run withheld, and the plain retry remains.
+ const db = await indexedDBManager.openDatabase({
+ name: DB_NAME,
+ version: 1,
+ stores: [{ name: STORE_NAME, keyPath: "fileId" }],
+ });
+ await new Promise<void>((resolve, reject) => {
+ const transaction = db.transaction([STORE_NAME], "readwrite");
+ transaction.oncomplete = () => resolve();
+ transaction.onerror = () => reject(transaction.error);
+ transaction.objectStore(STORE_NAME).put({
+ fileId: "f-old",
+ operation: "compress",
+ endpoint: "/api/v1/misc/compress-pdf",
+ params: {},
+ fileIds: ["f-old"],
+ recordedAt: 1,
+ });
+ });
+
+ expect((await loadRetryPayload("f-old"))?.replayUnfaithful).toBe(true);
});
it("stops descending into a pathologically deep object without exhausting the stack", async () => {
@@ -199,7 +268,7 @@ describe("the retry stash", () => {
for (let i = 0; i < 5000; i++) deep = { down: deep };
await expect(
- stashRetryPayload(payload({ params: { deep } })),
+ stashRetryPayload(stashable({ params: { deep } })),
).resolves.toBeUndefined();
expect(await loadRetryPayload("f-1")).not.toBeNull();
});
@@ -209,7 +278,7 @@ describe("the retry stash", () => {
let past: Record<string, unknown> = { password: "hunter2" };
for (let i = 0; i < 25; i++) past = { down: past };
- await stashRetryPayload(payload({ params: { past } }));
+ await stashRetryPayload(stashable({ params: { past } }));
// Where the walk gives up it must not hand back a subtree it never examined.
expect(JSON.stringify(await storedRecords())).not.toContain("hunter2");
@@ -221,7 +290,7 @@ describe("the retry stash", () => {
cyclic.self = cyclic;
await expect(
- stashRetryPayload(payload({ params: { cyclic } })),
+ stashRetryPayload(stashable({ params: { cyclic } })),
).resolves.toBeUndefined();
expect(await loadRetryPayload("f-1")).not.toBeNull();
});
@@ -365,3 +434,213 @@ describe("unlockLocalDocument", () => {
expect(result.message).not.toContain("wrong");
});
});
+
+/** The codes each server-side kind claims, which both sides assert against. */
+function sharedFixtureCodes(): Record<string, string[]> {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const fixture = resolve(
+ here,
+ "../../../../../testing/failure-kind-codes.json",
+ );
+ return JSON.parse(readFileSync(fixture, "utf8")).kinds;
+}
+
+describe("the mirrored error codes", () => {
+ it("claim exactly what the server claims", () => {
+ // A Java test cannot read this file, so the shared fixture is the tie between them: adding
+ // a code to the server without adding it here would match a stash to the wrong row.
+ expect(KIND_ERROR_CODES).toEqual(sharedFixtureCodes());
+ });
+
+ it("route every fixture code to its kind, and away from UNKNOWN", () => {
+ // The equality above compares the table; this proves the lookup built from it agrees, so a
+ // table that is right but read wrongly still fails.
+ for (const [kindId, codes] of Object.entries(sharedFixtureCodes())) {
+ for (const errorCode of codes) {
+ expect(stashMatchesKind(kindId, payload({ errorCode }))).toBe(true);
+ expect(stashMatchesKind("UNKNOWN", payload({ errorCode }))).toBe(false);
+ }
+ }
+ });
+});
+
+/** The stash is per file, but a file can carry only one; these say which row may claim it. */
+describe("stashMatchesKind", () => {
+ it("matches a kind against every code it claims, not just the first", async () => {
+ // E001 and E002 are both INPUT_CORRUPTED: a merge reports the second, a single load the first.
+ expect(
+ stashMatchesKind("INPUT_CORRUPTED", payload({ errorCode: "E001" })),
+ ).toBe(true);
+ expect(
+ stashMatchesKind("INPUT_CORRUPTED", payload({ errorCode: "E002" })),
+ ).toBe(true);
+ expect(
+ stashMatchesKind("INPUT_CORRUPTED", payload({ errorCode: "E003" })),
+ ).toBe(true);
+ expect(
+ stashMatchesKind("INPUT_CORRUPTED", payload({ errorCode: "E004" })),
+ ).toBe(false);
+ });
+
+ it("keeps a broken encryption apart from a missing password", async () => {
+ // Adjacent to a reader, unrelated to the fix: no password helps E003, no repair helps E004.
+ expect(
+ stashMatchesKind(
+ "INPUT_PASSWORD_PROTECTED",
+ payload({ errorCode: "E003" }),
+ ),
+ ).toBe(false);
+ });
+
+ it("gives an unclaimed code to UNKNOWN, and a claimed one never", async () => {
+ expect(stashMatchesKind("UNKNOWN", payload({ errorCode: "E005" }))).toBe(
+ true,
+ );
+ expect(stashMatchesKind("UNKNOWN", payload({ errorCode: null }))).toBe(
+ true,
+ );
+ expect(stashMatchesKind("UNKNOWN", payload({ errorCode: "E001" }))).toBe(
+ false,
+ );
+ });
+
+ it("refuses a kind that claims codes when the stash recorded none", async () => {
+ expect(
+ stashMatchesKind("INPUT_CORRUPTED", payload({ errorCode: null })),
+ ).toBe(false);
+ });
+});
+
+describe("retryInputIds", () => {
+ it("sends the whole batch for a multi-file endpoint, since that is what failed", async () => {
+ expect(
+ retryInputIds(
+ payload({ fileIds: ["f-1", "f-2"], multiFile: true }),
+ "f-2",
+ ),
+ ).toEqual(["f-1", "f-2"]);
+ });
+
+ it("sends only the document named for a one-file-per-call endpoint", async () => {
+ expect(
+ retryInputIds(
+ payload({ fileIds: ["f-1", "f-2"], multiFile: false }),
+ "f-2",
+ ),
+ ).toEqual(["f-2"]);
+ });
+
+ it("falls back to the first input when the named one was not part of the run", async () => {
+ expect(
+ retryInputIds(payload({ fileIds: ["f-1", "f-2"] }), "f-other"),
+ ).toEqual(["f-1"]);
+ });
+});
+
+describe("repairDocuments", () => {
+ it("repairs one document per call, since the endpoint takes one at a time", async () => {
+ getStirlingFiles.mockImplementation(async (ids: string[]) =>
+ ids.map((id) => new File(["%PDF-1.7"], `${id}.pdf`)),
+ );
+ post.mockResolvedValue({ data: new Blob(["fixed"]), headers: {} });
+
+ const result = await repairDocuments(["f-1", "f-2"]);
+
+ expect(result.ok).toBe(true);
+ expect(post).toHaveBeenCalledTimes(2);
+ expect((post.mock.calls[0] as [string])[0]).toBe("/api/v1/misc/repair");
+ // Paired back to the input, so each output versions the document it came from.
+ expect(result.repaired?.map((doc) => doc.fileId)).toEqual(["f-1", "f-2"]);
+ });
+
+ it("never sends a password, having none to send", async () => {
+ getStirlingFiles.mockResolvedValue([new File(["%PDF-1.7"], "doc.pdf")]);
+ post.mockResolvedValue({ data: new Blob(["fixed"]), headers: {} });
+
+ await repairDocuments(["f-1"]);
+
+ expect(
+ (post.mock.calls[0] as [string, FormData])[1].get("password"),
+ ).toBeNull();
+ });
+
+ it("fails the whole batch when one document cannot be repaired", async () => {
+ // All or nothing: a partial repair still fails the re-run.
+ getStirlingFiles.mockImplementation(async (ids: string[]) =>
+ ids.map((id) => new File(["%PDF-1.7"], `${id}.pdf`)),
+ );
+ post
+ .mockResolvedValueOnce({ data: new Blob(["fixed"]), headers: {} })
+ .mockRejectedValueOnce({ response: { data: "Repair failed." } });
+
+ const result = await repairDocuments(["f-1", "f-2"]);
+
+ expect(result.ok).toBe(false);
+ expect(result.message).toBe("Repair failed.");
+ expect(result.repaired).toBeUndefined();
+ });
+
+ it("reports the file is gone rather than repairing nothing quietly", async () => {
+ getStirlingFiles.mockResolvedValue([]);
+
+ const result = await repairDocuments(["f-1"]);
+
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe("fileMissing");
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it("refuses an empty list instead of reporting a vacuous success", async () => {
+ const result = await repairDocuments([]);
+
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe("fileMissing");
+ expect(post).not.toHaveBeenCalled();
+ });
+});
+
+/** The second half of a repair: the operation that failed, re-run over what repair produced. */
+describe("retryWithFiles", () => {
+ it("re-runs the stashed operation over the documents handed to it", async () => {
+ post.mockResolvedValue({ data: new Blob(["out"]), headers: {} });
+ const repaired = new File(["%PDF-1.7"], "doc_repaired.pdf");
+
+ const result = await retryWithFiles(
+ payload({
+ endpoint: "/api/v1/misc/compress-pdf",
+ params: { level: "5" },
+ }),
+ [repaired],
+ );
+
+ expect(result.ok).toBe(true);
+ const [path, formData] = post.mock.calls[0] as [string, FormData];
+ expect(path).toBe("/api/v1/misc/compress-pdf");
+ expect(formData.get("level")).toBe("5");
+ // The repaired bytes, not a re-read of the original from storage.
+ expect(formData.get("fileInput")).toBe(repaired);
+ expect(getStirlingFiles).not.toHaveBeenCalled();
+ });
+
+ it("sends every document at once, which is what a multi-file endpoint failed on", async () => {
+ post.mockResolvedValue({ data: new Blob(["out"]), headers: {} });
+
+ await retryWithFiles(payload({ multiFile: true }), [
+ new File(["a"], "a.pdf"),
+ new File(["b"], "b.pdf"),
+ ]);
+
+ expect(post).toHaveBeenCalledTimes(1);
+ expect(
+ (post.mock.calls[0] as [string, FormData])[1].getAll("fileInput"),
+ ).toHaveLength(2);
+ });
+
+ it("refuses when repair produced nothing to re-run", async () => {
+ const result = await retryWithFiles(payload(), []);
+
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe("fileMissing");
+ expect(post).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/core/services/notificationRetry.ts b/frontend/editor/src/core/services/notificationRetry.ts
index d57e6255a4..f971636d7a 100644
--- a/frontend/editor/src/core/services/notificationRetry.ts
+++ b/frontend/editor/src/core/services/notificationRetry.ts
@@ -5,43 +5,65 @@ import {
type DatabaseConfig,
} from "@app/services/indexedDBManager";
import { zipFileService } from "@app/services/zipFileService";
+import {
+ REMOVE_PASSWORD_ENDPOINT,
+ REPAIR_ENDPOINT,
+} from "@app/constants/toolEndpoints";
import type { FileId } from "@app/types/file";
-import type { ToolEndpoint } from "@app/types/toolApiTypes";
+import { uploadableFile } from "@app/utils/uploadableFile";
/** What the bell needs to retry a reported failure. The server keeps none of it. */
export interface RetryPayload {
operation: string;
endpoint: string;
+ /**
+ * The request body as the tool would post it, not the tool's own parameter model. A tool's UI
+ * names its settings for the user and maps them to the API's names on the way out, so the two
+ * differ freely: compress offers a compression level and posts an optimise level. Replaying
+ * the UI shape would send fields the server ignores and silently run the defaults instead.
+ */
params: Record<string, unknown>;
fileIds: string[];
/** Whether the endpoint takes the whole batch in one call, or one file per call. */
multiFile: boolean;
/** The failure's error code, so a stash can be matched to the row's kind. */
errorCode: string | null;
+ /**
+ * Whether replaying this stash would run something other than what failed, because a secret
+ * was dropped from it or because the tool exposes no mapping to its request body. A resolution
+ * must not re-run on those terms; the plain retry, which opens the tool, still can.
+ */
+ replayUnfaithful: boolean;
recordedAt: number;
}
-/** Mirrored from the server's `FailureKind` declarations. */
/**
- * Mirrors the codes each {@code FailureKind} claims, server-side. Pinned there by
- * `FailureKindTest#everyCodeAKindClaimsIsPinned`, which fails if a kind's codes change without
- * this moving with them.
+ * Mirrors the codes each `FailureKind` claims, server-side. Both copies are asserted against
+ * `testing/failure-kind-codes.json`, here and in `FailureKindTest`, so a code added to one side
+ * alone fails on the other.
+ *
+ * Exported for that conformance test: nothing else should read it, since a kind the server sends
+ * is an open string and `stashMatchesKind` already answers the only question worth asking.
*/
-const KIND_ERROR_CODES: Record<string, string> = {
- INPUT_PASSWORD_PROTECTED: "E004",
+export const KIND_ERROR_CODES: Record<string, readonly string[]> = {
+ INPUT_PASSWORD_PROTECTED: ["E004"],
+ INPUT_CORRUPTED: ["E001", "E002", "E003"],
+ COMPLIANCE_NOT_MET: ["E074"],
};
+/** 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 the one stash a file carries is the failure this row describes. */
export function stashMatchesKind(
kindId: string,
payload: RetryPayload,
): boolean {
const claimed = KIND_ERROR_CODES[kindId];
- if (claimed) return payload.errorCode === claimed;
- return (
- payload.errorCode === null ||
- !Object.values(KIND_ERROR_CODES).includes(payload.errorCode)
- );
+ if (claimed) {
+ return payload.errorCode !== null && claimed.includes(payload.errorCode);
+ }
+ return payload.errorCode === null || !CLAIMED_CODES.has(payload.errorCode);
}
/** Its own database: the files schema is at v9, and this hint is safe to lose. */
@@ -67,16 +89,26 @@ interface StoredRetryRecord extends RetryPayload {
/** Stripped on the way in: remove-password submits its password as a parameter. */
const SECRET_FIELD = /pass(word|phrase)|secret|token|credential/i;
-/** Never rejects: a browser refusing IndexedDB costs the retry button, not a second error. */
-export async function stashRetryPayload(payload: RetryPayload): Promise<void> {
+/**
+ * Never rejects: a browser refusing IndexedDB costs the retry button, not a second error.
+ *
+ * `paramsMapped` says whether `params` is the tool's request body or merely its UI model, which
+ * the caller knows and this cannot infer. False marks the stash unfaithful rather than refusing
+ * it, so the row keeps the plain retry even where nothing may re-run on its behalf.
+ */
+export async function stashRetryPayload(
+ payload: Omit<RetryPayload, "replayUnfaithful"> & { paramsMapped: boolean },
+): Promise<void> {
try {
const fileIds = payload.fileIds.filter(isUsableId);
if (!payload.operation.trim() || fileIds.length === 0) return;
+ const { paramsMapped, ...rest } = payload;
const record = {
- ...payload,
+ ...rest,
fileIds,
params: withoutSecrets(payload.params),
+ replayUnfaithful: !paramsMapped || containsSecret(payload.params),
};
await writeRecords(fileIds.map((fileId) => ({ ...record, fileId })));
@@ -107,9 +139,12 @@ export async function loadRetryPayload(
endpoint: record.endpoint,
params: record.params ?? {},
fileIds: record.fileIds ?? [fileId],
- // Older records predate these fields; both defaults fail closed.
+ // Older records predate these fields; every default fails closed. A record written before
+ // params were mapped holds the UI shape, so assuming it unfaithful is not merely cautious:
+ // it is what those records are. Only the automatic re-run is withheld, not the plain retry.
multiFile: record.multiFile ?? false,
errorCode: record.errorCode ?? null,
+ replayUnfaithful: record.replayUnfaithful ?? true,
recordedAt: record.recordedAt,
};
}
@@ -146,29 +181,37 @@ export interface RetryOutputFile {
}
/** Why a retry could not run; `serverMessage` means the message is the server's own words. */
-export type PasswordRetryFailure =
- | "notRetryable"
- | "fileMissing"
- | "serverMessage";
+export type RetryFailure = "notRetryable" | "fileMissing" | "serverMessage";
-/** What a password-carrying call comes back with. `files` only ever on success. */
-export interface PasswordRetryOutcome {
+/** What a retry call comes back with. `files` only ever on success. */
+export interface RetryOutcome {
ok: boolean;
- reason?: PasswordRetryFailure;
+ reason?: RetryFailure;
message?: string | null;
files?: RetryOutputFile[];
}
-/** Checked against the generated endpoints, so a renamed route fails the build here. */
-const UNLOCK_ENDPOINT =
- "/api/v1/security/remove-password" satisfies ToolEndpoint;
-
/** Unlock a held document for a failure with no stashed operation, e.g. a policy run. */
export async function unlockLocalDocument(
fileId: string,
password: string,
-): Promise<PasswordRetryOutcome> {
- return postWithPassword(UNLOCK_ENDPOINT, {}, [fileId], password);
+): Promise<RetryOutcome> {
+ return postDocuments(REMOVE_PASSWORD_ENDPOINT, {}, [fileId], password);
+}
+
+/** The inputs a retry of `payload` would send: the whole batch, or the one document named. */
+export function retryInputIds(
+ payload: RetryPayload,
+ forFileId: string | null = null,
+): string[] {
+ const ids = payload.multiFile
+ ? payload.fileIds
+ : [
+ forFileId && payload.fileIds.includes(forFileId)
+ ? forFileId
+ : payload.fileIds[0],
+ ];
+ return ids.filter(isUsableId);
}
/** Re-runs the stashed operation: `forFileId` alone, or the whole batch for a multi-file endpoint. */
@@ -176,29 +219,83 @@ export async function retryWithPassword(
payload: RetryPayload,
password: string,
forFileId: string | null = null,
-): Promise<PasswordRetryOutcome> {
+): Promise<RetryOutcome> {
if (!payload.endpoint) {
return { ok: false, reason: "notRetryable", message: null };
}
- const fileIds = payload.multiFile
- ? payload.fileIds
- : [
- forFileId && payload.fileIds.includes(forFileId)
- ? forFileId
- : payload.fileIds[0],
- ];
+ return postDocuments(
+ payload.endpoint,
+ payload.params,
+ retryInputIds(payload, forFileId),
+ password,
+ );
+}
+
+/** One document's repair, paired back to the id it was repaired from. */
+export interface RepairedDocument {
+ fileId: string;
+ file: RetryOutputFile;
+}
+
+/**
+ * As {@link RetryOutcome}, but the outputs stay paired to their inputs for versioning.
+ * `repaired` is only ever present on success.
+ */
+export interface RepairOutcome {
+ ok: boolean;
+ reason?: RetryFailure;
+ message?: string | null;
+ repaired?: RepairedDocument[];
+}
- return postWithPassword(payload.endpoint, payload.params, fileIds, password);
+/**
+ * Rewrites each held document through the repair tool. All or nothing: a re-run whose batch
+ * still holds one unrepaired input fails exactly as it did before, so a partial result is not
+ * worth adopting.
+ */
+export async function repairDocuments(
+ fileIds: readonly string[],
+): Promise<RepairOutcome> {
+ const usable = fileIds.filter(isUsableId);
+ if (usable.length === 0) {
+ return { ok: false, reason: "fileMissing", message: null };
+ }
+
+ const repaired: RepairedDocument[] = [];
+ // The endpoint takes one document and answers with one, so a batch is one call per file.
+ 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 };
+ }
+ const file = outcome.files?.[0];
+ if (!file) return { ok: false, reason: "notRetryable", message: null };
+ repaired.push({ fileId, file });
+ }
+ return { ok: true, repaired };
}
-/** Shared by both callers above, so a password reaches the network from one place only. */
-async function postWithPassword(
+/** Re-runs the stashed operation over documents this browser has just produced. */
+export async function retryWithFiles(
+ payload: RetryPayload,
+ files: File[],
+): Promise<RetryOutcome> {
+ if (!payload.endpoint) {
+ return { ok: false, reason: "notRetryable", message: null };
+ }
+ if (files.length === 0) {
+ return { ok: false, reason: "fileMissing", message: null };
+ }
+ return postFiles(payload.endpoint, payload.params, files, null);
+}
+
+async function postDocuments(
endpoint: string,
params: Record<string, unknown>,
requestedFileIds: (string | null | undefined)[],
- password: string,
-): Promise<PasswordRetryOutcome> {
+ password: string | null,
+): Promise<RetryOutcome> {
const fileIds = requestedFileIds.filter(isUsableId);
let files: File[] = [];
try {
@@ -212,9 +309,20 @@ async function postWithPassword(
return { ok: false, reason: "fileMissing", message: null };
}
+ // Restored from IndexedDB, which WebKit uploads as an empty body unless wrapped.
+ return postFiles(endpoint, params, files.map(uploadableFile), password);
+}
+
+/** The one place any of this reaches the network, so a password has a single path out. */
+async function postFiles(
+ endpoint: string,
+ params: Record<string, unknown>,
+ files: File[],
+ password: string | null,
+): Promise<RetryOutcome> {
try {
const formData = toFormData(params, files);
- formData.append("password", password);
+ if (password !== null) formData.append("password", password);
const response = await apiClient.post<Blob>(endpoint, formData, {
responseType: "blob",
});
@@ -311,6 +419,19 @@ function withoutSecrets(value: unknown): unknown {
return prunedBelow(value, 0);
}
+/** Whether {@link withoutSecrets} would drop anything: the same walk, answering rather than pruning. */
+function containsSecret(value: unknown, depth = 0): boolean {
+ if (depth >= MAX_PARAM_DEPTH) return false;
+ if (Array.isArray(value)) {
+ return value.some((item) => containsSecret(item, depth + 1));
+ }
+ if (value === null || typeof value !== "object") return false;
+ return Object.entries(value).some(
+ ([key, nested]) =>
+ SECRET_FIELD.test(key) || containsSecret(nested, depth + 1),
+ );
+}
+
function prunedBelow(value: unknown, depth: number): unknown {
if (depth >= MAX_PARAM_DEPTH) return TOO_DEEP;
if (Array.isArray(value))
diff --git a/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx b/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx
index 2754a6870b..32b5268f81 100644
--- a/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx
+++ b/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx
@@ -2,26 +2,35 @@ import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderHook } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
-import type {
- AppNotification,
- NotificationActionOffer,
-} from "@app/services/notifications";
-import type { NotificationActionContext } from "@core/components/notifications/notificationActions";
+import {
+ context,
+ inProcessor,
+ notification,
+ offer,
+ policyContext,
+} from "@app/components/notifications/resolutions/testSupport";
// Where each action sends the reader. Only the editor has the workbench contexts above it.
const retryWithPassword = vi.fn();
const unlockLocalDocument = vi.fn();
+const repairDocuments = vi.fn();
+const retryWithFiles = vi.fn();
vi.mock("@app/services/notificationRetry", async (importOriginal) => ({
- // The real stashMatchesKind: it is pure, and its guard is part of what these tests exercise.
+ // The real stashMatchesKind and retryInputIds: both are pure, and their guards are part of
+ // what these tests exercise.
...(await importOriginal<typeof import("@app/services/notificationRetry")>()),
retryWithPassword: (...args: unknown[]) => retryWithPassword(...args),
unlockLocalDocument: (...args: unknown[]) => unlockLocalDocument(...args),
+ repairDocuments: (...args: unknown[]) => repairDocuments(...args),
+ retryWithFiles: (...args: unknown[]) => retryWithFiles(...args),
}));
const rerunPolicy = vi.fn();
const rechainPolicyOnDocument = vi.fn();
+const canPlacePolicy = vi.fn();
vi.mock("@app/services/notificationPolicyRetry", () => ({
+ canPlacePolicy: (...args: unknown[]) => canPlacePolicy(...args),
rerunPolicy: (...args: unknown[]) => rerunPolicy(...args),
rechainPolicyOnDocument: (...args: unknown[]) =>
rechainPolicyOnDocument(...args),
@@ -96,77 +105,6 @@ const setSelectedFiles = vi.fn();
const addFiles = vi.fn();
const consumeFiles = vi.fn();
-function notification(
- overrides: Partial<AppNotification> = {},
-): AppNotification {
- return {
- id: "failure:evt-1",
- source: "FAILURE",
- kindId: "INPUT_PASSWORD_PROTECTED",
- origin: "TOOL",
- ownership: "MINE",
- severity: "ERROR",
- status: "NEW",
- titleKey: "portal.failures.kind.inputPasswordProtected.title",
- defaultTitle: "Password-protected document",
- detail: "The PDF Document is passworded",
- fileId: "f-1",
- sourceId: null,
- policyId: null,
- occurrences: 3,
- createdAt: "2026-08-06T00:00:00Z",
- lastSeenAt: "2026-08-06T00:00:00Z",
- actions: [],
- ...overrides,
- };
-}
-
-function offer(id: string): NotificationActionOffer {
- return {
- id,
- labelKey: `portal.failures.action.${id.toLowerCase()}`,
- defaultLabel: id,
- slot: "SECONDARY",
- enabled: true,
- disabledReasonKey: null,
- };
-}
-
-function context(
- overrides: Partial<NotificationActionContext> = {},
-): NotificationActionContext {
- return {
- notification: notification(),
- hasLocalFile: true,
- retryPayload: {
- operation: "removePassword",
- endpoint: "/api/v1/security/remove-password",
- params: {},
- fileIds: ["f-1"],
- multiFile: false,
- errorCode: "E004",
- recordedAt: 0,
- },
- ...overrides,
- };
-}
-
-/** An attended policy run: the row names the policy and the document, and nothing was stashed. */
-function policyContext(
- overrides: Partial<NotificationActionContext> = {},
-): NotificationActionContext {
- return {
- notification: notification({
- origin: "POLICY",
- policyId: "pol-1",
- sourceId: null,
- }),
- hasLocalFile: true,
- retryPayload: null,
- ...overrides,
- };
-}
-
/** The editor shell: the workbench's providers all sit above the bell. */
const inEditor = ({ children }: { children: ReactNode }) => (
<MemoryRouter>
@@ -204,25 +142,10 @@ const inEditor = ({ children }: { children: ReactNode }) => (
</MemoryRouter>
);
-/** The processor shell: the portal mounts above the app's providers, so there is none. */
-const inProcessor = ({ children }: { children: ReactNode }) => (
- <MemoryRouter>{children}</MemoryRouter>
-);
-
function registry(wrapper = inEditor) {
return renderHook(() => useNotificationActions(), { wrapper }).result.current;
}
-/** A file's own bytes. Via FileReader because this environment's Blob has no `text`. */
-function bytesOf(file: File): Promise<string> {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () => resolve(String(reader.result));
- reader.onerror = () => reject(reader.error);
- reader.readAsText(file);
- });
-}
-
beforeEach(() => {
navigate.mockReset();
addStirlingFileStubs.mockReset().mockResolvedValue([]);
@@ -248,12 +171,28 @@ beforeEach(() => {
},
],
});
+ // The repair succeeds by default: most cases below are about what happens afterwards.
+ repairDocuments.mockReset().mockResolvedValue({
+ ok: true,
+ repaired: [
+ {
+ fileId: "f-1",
+ file: {
+ blob: new Blob(["repaired"], { type: "application/pdf" }),
+ filename: "invoice_repaired.pdf",
+ },
+ },
+ ],
+ });
+ retryWithFiles.mockReset().mockResolvedValue({ ok: true, files: [] });
// Tracked by default: something is polling the run, so its output will arrive.
rerunPolicy.mockReset().mockResolvedValue({ ok: true, tracked: true });
rechainPolicyOnDocument.mockReset().mockResolvedValue({
ok: true,
tracked: true,
});
+ // Placeable by default: the browser still holds the policy the failure names.
+ canPlacePolicy.mockReset().mockReturnValue(true);
window.sessionStorage.clear();
window.history.pushState({}, "", "/");
});
@@ -282,6 +221,7 @@ describe("useNotificationActions", () => {
fileIds: ["f-1"],
multiFile: false,
errorCode: "E004",
+ replayUnfaithful: false,
recordedAt: 0,
},
}),
@@ -432,139 +372,6 @@ describe("useNotificationActions", () => {
expect(setToolAndWorkbench).not.toHaveBeenCalled();
});
- it("unlocks with the password it was given and reports what came back", async () => {
- retryWithPassword.mockResolvedValue({ ok: false, message: "Wrong" });
-
- const outcome = await registry().DECRYPT?.run(context(), "hunter2");
-
- expect(retryWithPassword).toHaveBeenCalledWith(
- expect.objectContaining({ endpoint: "/api/v1/security/remove-password" }),
- "hunter2",
- // The row's own document, so a single-file endpoint is not handed the whole batch.
- "f-1",
- );
- expect(outcome).toEqual({ ok: false, message: "Wrong" });
- });
-
- it("takes the unlocked document into the workbench through FileContext", async () => {
- // The whole point of the password: the user must end up holding the unlocked file.
- retryWithPassword.mockResolvedValue({
- ok: true,
- files: [
- {
- blob: new Blob(["pdf"], { type: "application/pdf" }),
- filename: "invoice.pdf",
- },
- ],
- });
-
- const outcome = await registry().DECRYPT?.run(context(), "hunter2");
-
- expect(outcome).toEqual({ ok: true });
- const [files, options] = addFiles.mock.calls[0];
- expect((files as File[]).map((file) => file.name)).toEqual(["invoice.pdf"]);
- // Selected so it is on screen, and marked in-app so `usePolicyAutoRun` leaves it alone.
- expect(options).toEqual({ selectFiles: true, derivedFromTool: true });
- // And closed with the prefixed id: nothing else tells the server the client fixed it.
- expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1");
- });
-
- it("replaces the encrypted original in place when it is open in the workbench", async () => {
- // The failed document is on screen, so the unlock versions it rather than adding a second copy.
- openFileIds = ["f-1"];
- openFilesById = {
- "f-1": { id: "f-1", name: "invoice.pdf", versionNumber: 1 },
- };
- unlockLocalDocument.mockResolvedValue({
- ok: true,
- files: [
- {
- blob: new Blob(["pdf"], { type: "application/pdf" }),
- filename: "invoice.pdf",
- },
- ],
- });
-
- const outcome = await registry().DECRYPT?.run(policyContext(), "hunter2");
-
- expect(outcome).toEqual({ ok: true });
- // Consumed, not added: the encrypted original is versioned, so there is only ever one document.
- expect(addFiles).not.toHaveBeenCalled();
- const [inputIds, , stubs] = consumeFiles.mock.calls[0];
- expect(inputIds).toEqual(["f-1"]);
- // Still in-app, so usePolicyAutoRun does not enforce the chain on it — the rechain does that.
- expect(
- (stubs as Array<{ derivedFromTool?: boolean }>)[0].derivedFromTool,
- ).toBe(true);
- });
-
- it("versions a document the workbench has closed, rather than adding a copy of it", async () => {
- // Closed in the sidebar but still on the device: adding here left the user holding both.
- openFileIds = [];
- openFilesById = {};
-
- await registry().DECRYPT?.run(policyContext(), "hunter2");
-
- expect(addFiles).not.toHaveBeenCalled();
- expect(consumeFiles.mock.calls[0][0]).toEqual(["f-1"]);
- });
-
- it("adds the unlocked document when nothing on this device holds the original", async () => {
- // No stub anywhere: there is no version chain to extend, so adding is all that is left.
- h.getStirlingFileStub.mockResolvedValue(null);
-
- await registry().DECRYPT?.run(policyContext(), "hunter2");
-
- expect(consumeFiles).not.toHaveBeenCalled();
- expect(addFiles.mock.calls[0][1]).toEqual({
- selectFiles: true,
- derivedFromTool: true,
- });
- });
-
- it("closes the incident only once the document is safely in", async () => {
- // Reported first, then a failed adoption, would leave the row closed with nothing to show.
- retryWithPassword.mockResolvedValue({
- ok: true,
- files: [{ blob: new Blob(["pdf"]), filename: "invoice.pdf" }],
- });
- addFiles.mockRejectedValue(new Error("quota"));
-
- await registry().DECRYPT?.run(context(), "hunter2");
-
- expect(reportNotificationResolved).not.toHaveBeenCalled();
- });
-
- it("keeps the unlock a success when the server will not record it", async () => {
- // The document is already in the workbench, so a refused resolve is not a failed unlock.
- retryWithPassword.mockResolvedValue({
- ok: true,
- files: [{ blob: new Blob(["pdf"]), filename: "invoice.pdf" }],
- });
- reportNotificationResolved.mockResolvedValue(false);
-
- expect(await registry().DECRYPT?.run(context(), "hunter2")).toEqual({
- ok: true,
- });
- });
-
- it("reports a failure when the unlocked document cannot be taken in", async () => {
- // Unlocked but dropped leaves the user with nothing, so it is never reported as success.
- retryWithPassword.mockResolvedValue({
- ok: true,
- files: [{ blob: new Blob(["pdf"]), filename: "invoice.pdf" }],
- });
- addFiles.mockRejectedValue(new Error("quota"));
-
- const outcome = await registry().DECRYPT?.run(context(), "hunter2");
-
- expect(outcome).toEqual({
- ok: false,
- message:
- "The document was unlocked but could not be opened here. Try the tool directly.",
- });
- });
-
it("offers no unlock where there is nowhere to put the result", async () => {
// No FileContext there, so an unlocked document would have nowhere to go.
const actions = registry(inProcessor);
@@ -579,13 +386,6 @@ describe("useNotificationActions", () => {
expect(retryWithPassword).not.toHaveBeenCalled();
});
- it("offers the unlock where the editor can take the result", () => {
- expect(registry().DECRYPT?.available(context())).toBe(true);
- expect(
- registry().DECRYPT?.available(context({ hasLocalFile: false })),
- ).toBe(false);
- });
-
it("says it cannot hand the document over rather than navigating to nothing", async () => {
// Spied on the prototype: jsdom's storage is a proxy, so an own-property spy does not take.
const setItem = vi
@@ -606,19 +406,6 @@ describe("useNotificationActions", () => {
setItem.mockRestore();
});
- it("says so rather than posting nothing when the stash has gone", async () => {
- const outcome = await registry().DECRYPT?.run(
- context({ retryPayload: null }),
- "hunter2",
- );
-
- expect(retryWithPassword).not.toHaveBeenCalled();
- expect(outcome).toEqual({
- ok: false,
- message: "This document can no longer be retried from this browser.",
- });
- });
-
it("links to the processor's review screen", () => {
registry().VIEW_IN_PROCESSOR?.run(context());
@@ -670,6 +457,21 @@ describe("retrying an attended policy run", () => {
expect(retryWithPassword).not.toHaveBeenCalled();
});
+ it("submits nothing when the policy cannot be placed, so an unresolvable row stops billing", async () => {
+ // Same leak as the resolutions, reached through the plain retry: the run is chargeable and
+ // its output is uncollectable, and the row it fails to close keeps the button on offer.
+ canPlacePolicy.mockReturnValue(false);
+ const row = policyContext();
+
+ expect(registry().OPEN_IN_TOOL?.available?.(row)).toBe(false);
+
+ expect(await registry().OPEN_IN_TOOL?.run(row)).toEqual({
+ ok: false,
+ message: "This document can no longer be retried from this browser.",
+ });
+ expect(rerunPolicy).not.toHaveBeenCalled();
+ });
+
it("re-runs the policy rather than reopening a tool, even where a stash happens to exist", async () => {
// An earlier tool failure may have left a stash, but the row is about the policy.
await registry().OPEN_IN_TOOL?.run(
@@ -681,6 +483,7 @@ describe("retrying an attended policy run", () => {
fileIds: ["f-1"],
multiFile: false,
errorCode: "E004",
+ replayUnfaithful: false,
recordedAt: 0,
},
}),
@@ -777,85 +580,6 @@ describe("retrying an attended policy run", () => {
expect(rerunPolicy).not.toHaveBeenCalled();
});
- it("unlocks, takes the document in, runs the policy again, then closes the incident", async () => {
- const order: string[] = [];
- consumeFiles.mockImplementation(async () => {
- order.push("adopt");
- return ["f-unlocked"];
- });
- rechainPolicyOnDocument.mockImplementation(async () => {
- order.push("rerun");
- return { ok: true, tracked: true };
- });
- reportNotificationResolved.mockImplementation(async () => {
- order.push("resolve");
- return true;
- });
-
- const outcome = await registry().DECRYPT?.run(policyContext(), "hunter2");
-
- expect(outcome).toEqual({ ok: true });
- // The unlock is the remove-password call on the document the row names, not a stashed endpoint.
- expect(unlockLocalDocument).toHaveBeenCalledWith("f-1", "hunter2");
- // Versioned onto the encrypted original, so there is one document rather than two.
- expect(addFiles).not.toHaveBeenCalled();
- const [inputIds, files, stubs] = consumeFiles.mock.calls[0];
- expect(inputIds).toEqual(["f-1"]);
- expect((files as File[]).map((file) => file.name)).toEqual(["invoice.pdf"]);
- // derivedFromTool stops the adoption starting a SECOND, billed run of this same policy.
- expect(
- (stubs as Array<{ derivedFromTool?: boolean }>)[0].derivedFromTool,
- ).toBe(true);
- // Under the ORIGINAL reference so a repeat folds on, with the output on the ADOPTED document.
- expect(rechainPolicyOnDocument).toHaveBeenCalledWith(
- { policyId: "pol-1", fileId: "f-1" },
- expect.any(File),
- "f-unlocked",
- );
- // And with the prefixed notification id, never a raw failure id.
- expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1");
- expect(order).toEqual(["adopt", "rerun", "resolve"]);
- });
-
- it("starts exactly one run for one click", async () => {
- await registry().DECRYPT?.run(policyContext(), "hunter2");
-
- // One submission: the adoption's is silenced by derivedFromTool above.
- expect(rechainPolicyOnDocument).toHaveBeenCalledTimes(1);
- expect(rerunPolicy).not.toHaveBeenCalled();
- expect(consumeFiles.mock.calls[0][2][0]).toMatchObject({
- derivedFromTool: true,
- });
- });
-
- it("still runs when the adoption reports no workspace id, rather than guessing one", async () => {
- // Nothing to attribute the output to, so the run goes untracked rather than to the original.
- consumeFiles.mockResolvedValue([]);
- rechainPolicyOnDocument.mockResolvedValue({ ok: true, tracked: false });
-
- await registry().DECRYPT?.run(policyContext(), "hunter2");
-
- expect(rechainPolicyOnDocument).toHaveBeenCalledWith(
- { policyId: "pol-1", fileId: "f-1" },
- expect.any(File),
- null,
- );
- });
-
- it("leaves the row open when the re-run cannot deliver, and says why", async () => {
- // Untracked, so the processed document never arrives: the unlocked input is not the point.
- rechainPolicyOnDocument.mockResolvedValue({ ok: true, tracked: false });
-
- expect(await registry().DECRYPT?.run(policyContext(), "hunter2")).toEqual({
- ok: false,
- message:
- "The document was unlocked and the policy re-run started, but its result cannot be delivered here, so this failure stays open.",
- });
- // Adopted regardless: the password bought them the unlocked document either way.
- expect(consumeFiles).toHaveBeenCalled();
- expect(reportNotificationResolved).not.toHaveBeenCalled();
- });
-
it("says an untracked plain re-run cannot be delivered either", async () => {
// Same hole without a password: the cache could not place the policy, so nothing polls the run.
rerunPolicy.mockResolvedValue({ ok: true, tracked: false });
@@ -867,69 +591,4 @@ describe("retrying an attended policy run", () => {
});
expect(reportNotificationResolved).not.toHaveBeenCalled();
});
-
- it("shows a wrong password for what it is, and touches nothing else", async () => {
- unlockLocalDocument.mockResolvedValue({
- ok: false,
- message: "The password is incorrect.",
- });
-
- expect(await registry().DECRYPT?.run(policyContext(), "wrong")).toEqual({
- ok: false,
- message: "The password is incorrect.",
- });
- expect(addFiles).not.toHaveBeenCalled();
- expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
- // The row is still a failure, so nothing may report it fixed.
- expect(reportNotificationResolved).not.toHaveBeenCalled();
- });
-
- it("neither re-runs nor closes the incident when the document cannot be taken in", async () => {
- consumeFiles.mockRejectedValue(new Error("quota"));
-
- expect(await registry().DECRYPT?.run(policyContext(), "hunter2")).toEqual({
- ok: false,
- message:
- "The document was unlocked but could not be opened here. Try the tool directly.",
- });
- expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
- expect(reportNotificationResolved).not.toHaveBeenCalled();
- });
-
- it("says the unlock worked but the re-run did not, and leaves the row open", async () => {
- rechainPolicyOnDocument.mockResolvedValue({
- ok: false,
- reason: "rejected",
- message: "Queue full.",
- });
-
- expect(await registry().DECRYPT?.run(policyContext(), "hunter2")).toEqual({
- ok: false,
- message:
- "The document was unlocked and opened here, but the policy could not be run on it again.",
- });
- // Adopted anyway: the password bought them the unlocked document, and that is theirs to keep.
- expect(consumeFiles).toHaveBeenCalled();
- // But nothing is fixed server-side, so the incident stays open.
- expect(reportNotificationResolved).not.toHaveBeenCalled();
- });
-
- it("never hands the password to anything but the unlock", async () => {
- await registry().DECRYPT?.run(policyContext(), "hunter2");
-
- // Everything downstream of the unlock: no payload, stash or id carries the password.
- const downstream = [
- ...addFiles.mock.calls,
- ...rechainPolicyOnDocument.mock.calls,
- ...reportNotificationResolved.mock.calls,
- ];
- expect(JSON.stringify(downstream)).not.toContain("hunter2");
- // Not in the file that goes back to the policy either: those are the server's unlocked bytes.
- const [, document] = rechainPolicyOnDocument.mock.calls[0] as [
- unknown,
- File,
- unknown,
- ];
- expect(await bytesOf(document)).not.toContain("hunter2");
- });
});
diff --git a/frontend/editor/src/proprietary/components/notifications/notificationActions.ts b/frontend/editor/src/proprietary/components/notifications/notificationActions.ts
index dc34d828a0..462c7a53d4 100644
--- a/frontend/editor/src/proprietary/components/notifications/notificationActions.ts
+++ b/frontend/editor/src/proprietary/components/notifications/notificationActions.ts
@@ -15,33 +15,18 @@ import {
} from "@app/routes/portalBasename";
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
import { fileStorage } from "@app/services/fileStorage";
-import {
- clearRetryPayload,
- retryWithPassword,
- stashMatchesKind,
- unlockLocalDocument,
- type PasswordRetryOutcome,
- type RetryOutputFile,
- type RetryPayload,
-} from "@app/services/notificationRetry";
-import {
- rerunPolicy,
- rechainPolicyOnDocument,
- type PolicyRerunOutcome,
- type PolicyRetryTarget,
-} from "@app/services/notificationPolicyRetry";
-import { reportNotificationResolved } from "@app/services/notifications";
-import {
- createChildStub,
- generateProcessedFileMetadata,
-} from "@app/contexts/file/fileActions";
+import { rerunPolicy } from "@app/services/notificationPolicyRetry";
import { isValidToolId, type ToolId } from "@app/types/toolId";
+import type { FileId } from "@app/types/file";
import {
- createStirlingFile,
- type FileContextActions,
- type StirlingFileStub,
-} from "@app/types/fileContext";
-import type { FileId, ToolOperation } from "@app/types/file";
+ RESOLUTIONS,
+ canRetry,
+ rerunOutcome,
+ resolutionSpec,
+ retryTargetOf,
+ toolOf,
+ unavailable,
+} from "@app/components/notifications/resolutions";
import {
type ClientActionOutcome,
type ClientActionRegistry,
@@ -103,87 +88,6 @@ function goToEditor(path: string): void {
window.dispatchEvent(new PopStateEvent("popstate"));
}
-/** The stashed `params` stay stashed: `useBaseParameters` has no seam for initial values. */
-function toolOf(payload: RetryPayload): ToolId | null {
- return isValidToolId(payload.operation) ? payload.operation : null;
-}
-
-/** A tool retry is an endpoint plus client-held parameters; a policy retry is a stored pair. */
-type RetryTarget =
- | { readonly kind: "tool"; readonly payload: RetryPayload }
- | { readonly kind: "policy"; readonly policy: PolicyRetryTarget };
-
-/** Which of the two a notification describes, or null when nothing here can re-run it. */
-function retryTargetOf(context: NotificationActionContext): RetryTarget | null {
- const { notification, hasLocalFile, retryPayload } = context;
- if (!hasLocalFile) return null;
-
- // The policy shape wins where it applies, being the more specific claim.
- const attended = (notification.sourceId ?? null) === null;
- if (attended && notification.policyId && notification.fileId) {
- return {
- kind: "policy",
- policy: { policyId: notification.policyId, fileId: notification.fileId },
- };
- }
-
- // One stash per file, but one incident per kind per file, so the stash may be another row's.
- return retryPayload && stashMatchesKind(notification.kindId, retryPayload)
- ? { kind: "tool", payload: retryPayload }
- : null;
-}
-
-function asFiles(outputs: RetryOutputFile[]): File[] {
- return outputs.map(
- (output) =>
- new File([output.blob], output.filename, {
- type: output.blob.type || "application/pdf",
- }),
- );
-}
-
-/** Versions the original in place; `derivedFromTool` keeps `usePolicyAutoRun` off the result. */
-async function adopt(
- actions: FileContextActions,
- parentStub: StirlingFileStub | null,
- files: File[],
-): Promise<FileId[]> {
- const unlocked = files[0];
- if (!unlocked) return [];
-
- if (!parentStub) {
- const added = await actions.addFiles([unlocked], {
- selectFiles: true,
- derivedFromTool: true,
- });
- return added.map((file) => file.fileId);
- }
-
- const metadata = await generateProcessedFileMetadata(unlocked);
- const operation: ToolOperation = {
- toolId: "removePassword",
- timestamp: Date.now(),
- };
- const childStub: StirlingFileStub = {
- ...createChildStub(
- parentStub,
- operation,
- unlocked,
- metadata?.thumbnailUrl,
- metadata,
- ),
- derivedFromTool: true,
- };
- const stirlingFile = createStirlingFile(unlocked, childStub.id);
- const outputIds = await actions.consumeFiles(
- [parentStub.id],
- [stirlingFile],
- [childStub],
- );
- actions.setSelectedFiles(outputIds);
- return outputIds;
-}
-
export function useNotificationActions(): ClientActionRegistry {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -193,7 +97,6 @@ export function useNotificationActions(): ClientActionRegistry {
const navigation = useContext(NavigationActionsContext);
const viewer = useContext(ViewerContext);
const canOpenHere = Boolean(fileContext && fileStore && navigation && viewer);
- // The upload chain a retry rejoins excludes Classification when the engine is off.
/** Opens the way the file sidebar does: an id the workbench does not hold renders nothing. */
const openInWorkbench = useCallback(
@@ -259,7 +162,7 @@ export function useNotificationActions(): ClientActionRegistry {
if (canOpenHere && fileId) {
return (await openInWorkbench(fileId, tool))
? undefined
- : unavailable();
+ : unavailable(t);
}
if (fileId && !stashSelection(fileId, tool)) {
// Nothing would be open on arrival, so say so rather than navigate regardless.
@@ -274,94 +177,12 @@ export function useNotificationActions(): ClientActionRegistry {
goToEditor(tool ? getToolUrlPath(tool) : EDITOR_BASENAME);
};
- const unavailable = (): ClientActionOutcome => ({
- ok: false,
- message: t(
- "notifications.retryUnavailable",
- "This document can no longer be retried from this browser.",
- ),
- });
-
- /** The service reports why and this layer words it, because the wording belongs where `t` is. */
- const unlockFailure = (
- outcome: PasswordRetryOutcome,
- ): ClientActionOutcome => {
- if (outcome.reason === "fileMissing") {
- return {
- ok: false,
- message: t(
- "notifications.notOnThisDevice",
- "This document is not on this device, so it cannot be opened or retried here.",
- ),
- };
- }
- if (outcome.reason === "notRetryable") return unavailable();
- // The server's own words, or nothing: the row falls back to its generic failure line.
- return { ok: false, message: outcome.message ?? undefined };
- };
-
- /** An untracked run is a failure on purpose: nothing here will collect what it produces. */
- const rerunOutcome = (
- outcome: PolicyRerunOutcome,
- adopted: boolean,
- ): ClientActionOutcome => {
- if (outcome.ok && outcome.tracked) return { ok: true };
- if (outcome.ok) {
- return {
- ok: false,
- message: adopted
- ? t(
- "notifications.unlockedRerunUndelivered",
- "The document was unlocked and the policy re-run started, but its result cannot be delivered here, so this failure stays open.",
- )
- : t(
- "notifications.rerunUndelivered",
- "The policy re-run started, but its result cannot be delivered here, so this failure stays open.",
- ),
- };
- }
- if (outcome.reason === "missingFile") {
- return {
- ok: false,
- message: t(
- "notifications.notOnThisDevice",
- "This document is not on this device, so it cannot be opened or retried here.",
- ),
- };
- }
- if (adopted) {
- return {
- ok: false,
- message: t(
- "notifications.unlockedNotRerun",
- "The document was unlocked and opened here, but the policy could not be run on it again.",
- ),
- };
- }
- return {
- ok: false,
- message:
- outcome.message ??
- t(
- "notifications.rerunRejected",
- "The policy could not be run again just now. Try again in a moment.",
- ),
- };
- };
-
- /** A policy re-run also needs the editor's providers, to collect its output. */
- const canRetry = (context: NotificationActionContext): boolean => {
- const target = retryTargetOf(context);
- if (!target) return false;
- return target.kind === "tool" || fileContext !== undefined;
- };
-
const openInTool: ClientActionSpec = {
- available: canRetry,
+ available: (context) => canRetry(context, fileContext),
closesPanel: true,
run: async (context): Promise<ClientActionOutcome | void> => {
const target = retryTargetOf(context);
- if (!target) return unavailable();
+ if (!target) return unavailable(t);
// A tool opens rather than re-runs: it failed once, so the user sees the settings first.
if (target.kind === "tool") {
@@ -370,76 +191,8 @@ export function useNotificationActions(): ClientActionRegistry {
toolOf(target.payload),
);
}
- if (!fileContext) return unavailable();
- return rerunOutcome(await rerunPolicy(target.policy), false);
- },
- };
-
- const decrypt: ClientActionSpec = {
- // In the processor shell an unlocked document has nowhere to go, so the row promotes on.
- available: (context) => fileContext !== undefined && canRetry(context),
- needsPassword: true,
- // On success the adopted document is the destination, and it is behind the panel.
- closesPanel: true,
- run: async (context, password): Promise<ClientActionOutcome> => {
- const target = retryTargetOf(context);
- if (!target || !password || !fileContext) return unavailable();
-
- // The stash knows a tool's parameters; a locked policy input just needs unlocking.
- const outcome =
- target.kind === "tool"
- ? await retryWithPassword(
- target.payload,
- password,
- context.notification.fileId,
- )
- : await unlockLocalDocument(target.policy.fileId, password);
- if (!outcome.ok) return unlockFailure(outcome);
-
- // A failed adoption fails the action: dropping the result leaves them nothing.
- const unlocked = asFiles(outcome.files ?? []);
- // Only a policy names an original to version; a tool retry keeps adding its output.
- const originalId =
- target.kind === "policy" ? (target.policy.fileId as FileId) : null;
- // Storage too, or a file merely closed in the sidebar gets decrypted twice over.
- const parentStub = originalId
- ? (fileStore?.getState().files.byId?.[originalId] ??
- (await fileStorage.getStirlingFileStub(originalId)) ??
- null)
- : null;
- let adopted: FileId[] = [];
- try {
- adopted = await adopt(fileContext.actions, parentStub, unlocked);
- } catch {
- return {
- ok: false,
- message: t(
- "notifications.adoptFailed",
- "The document was unlocked but could not be opened here. Try the tool directly.",
- ),
- };
- }
-
- // Under the ORIGINAL reference so a repeat folds on, and after the adoption.
- if (target.kind === "policy") {
- const document = unlocked[0];
- const rerun: PolicyRerunOutcome = document
- ? await rechainPolicyOnDocument(
- target.policy,
- document,
- adopted[0] ?? null,
- )
- : { ok: false, reason: "missingFile" };
- // Anything short of a tracked run stops here: the input alone is not the result.
- const result = rerunOutcome(rerun, true);
- if (!result.ok) return result;
- }
-
- // Ignored on purpose: a refused resolve is not a failed unlock.
- await reportNotificationResolved(context.notification.id);
- // The stash described the run that just succeeded, so it has nothing left to offer.
- await clearRetryPayload(context.notification.fileId);
- return { ok: true };
+ if (!fileContext) return unavailable(t);
+ return rerunOutcome(t, await rerunPolicy(target.policy), null);
},
};
@@ -455,9 +208,16 @@ export function useNotificationActions(): ClientActionRegistry {
run: () => navigate(REVIEW_DESTINATION),
};
+ const resolutions = Object.fromEntries(
+ RESOLUTIONS.map((resolution) => [
+ resolution.actionId,
+ resolutionSpec(resolution, { t, fileContext, fileStore }),
+ ]),
+ );
+
return {
OPEN_IN_TOOL: openInTool,
- DECRYPT: decrypt,
+ ...resolutions,
VIEW_FILE: viewFile,
VIEW_IN_PROCESSOR: viewInProcessor,
};
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/adopt.ts b/frontend/editor/src/proprietary/components/notifications/resolutions/adopt.ts
new file mode 100644
index 0000000000..1fb12aca3b
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/adopt.ts
@@ -0,0 +1,42 @@
+import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
+import type { FileId } from "@app/types/file";
+import type {
+ FileContextActions,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { ToolId } from "@app/types/toolId";
+
+// Both mark the result `derivedFromTool`, which keeps `usePolicyAutoRun` off it.
+
+/** Adds a produced document on its own, selected so it is on screen. */
+export async function addToWorkbench(
+ actions: FileContextActions,
+ file: File,
+): Promise<FileId[]> {
+ const added = await actions.addFiles([file], {
+ selectFiles: true,
+ derivedFromTool: true,
+ });
+ return added.map((added) => added.fileId);
+}
+
+/** Versions `parentStub` in place with `file`, attributed to `toolId` in its history. */
+export async function versionUnder(
+ actions: FileContextActions,
+ parentStub: StirlingFileStub,
+ file: File,
+ toolId: ToolId,
+): Promise<FileId[]> {
+ const { stirlingFiles, stubs } = await createStirlingFilesAndStubs(
+ [file],
+ parentStub,
+ toolId,
+ );
+ const outputIds = await actions.consumeFiles(
+ [parentStub.id],
+ stirlingFiles,
+ stubs.map((stub) => ({ ...stub, derivedFromTool: true })),
+ );
+ actions.setSelectedFiles(outputIds);
+ return outputIds;
+}
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/index.ts b/frontend/editor/src/proprietary/components/notifications/resolutions/index.ts
new file mode 100644
index 0000000000..10707e3e2c
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/index.ts
@@ -0,0 +1,41 @@
+import type { ToolId } from "@app/types/toolId";
+import { repair } from "@app/components/notifications/resolutions/repair";
+import type { Resolution } from "@app/components/notifications/resolutions/resolution";
+import { unlock } from "@app/components/notifications/resolutions/unlock";
+
+export {
+ canRetry,
+ rerunOutcome,
+ resolutionSpec,
+ retryTargetOf,
+ toolOf,
+ unavailable,
+ type Resolution,
+ type ResolutionActionId,
+ type ResolutionDeps,
+ type RetryTarget,
+} from "@app/components/notifications/resolutions/resolution";
+
+/**
+ * Every fix this build can run. The action registry and the manual-run continuation both derive
+ * from this list, so a new server kind that reuses an existing action needs no client change.
+ */
+export const RESOLUTIONS: readonly Resolution[] = [unlock, repair];
+
+const TOOL_BY_ACTION = new Map<string, ToolId>(
+ RESOLUTIONS.map((resolution) => [resolution.actionId, resolution.toolId]),
+);
+
+const RESOLVING_TOOLS = new Set<string>(
+ RESOLUTIONS.map((resolution) => resolution.toolId),
+);
+
+/** The tool whose manual run counts as the resolution `actionId` offers, if any does. */
+export function resolvingToolFor(actionId: string): ToolId | null {
+ return TOOL_BY_ACTION.get(actionId) ?? null;
+}
+
+/** Whether a successful run of `operation` could be some open row's resolution. */
+export function isResolvingTool(operation: string): boolean {
+ return RESOLVING_TOOLS.has(operation);
+}
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/repair.test.tsx b/frontend/editor/src/proprietary/components/notifications/resolutions/repair.test.tsx
new file mode 100644
index 0000000000..08f1c929a6
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/repair.test.tsx
@@ -0,0 +1,449 @@
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import {
+ bytesOf,
+ context,
+ inProcessor,
+ policyContext,
+} from "@app/components/notifications/resolutions/testSupport";
+
+// Where each action sends the reader. Only the editor has the workbench contexts above it.
+
+const retryWithPassword = vi.fn();
+const unlockLocalDocument = vi.fn();
+const repairDocuments = vi.fn();
+const retryWithFiles = vi.fn();
+vi.mock("@app/services/notificationRetry", async (importOriginal) => ({
+ // The real stashMatchesKind and retryInputIds: both are pure, and their guards are part of
+ // what these tests exercise.
+ ...(await importOriginal<typeof import("@app/services/notificationRetry")>()),
+ retryWithPassword: (...args: unknown[]) => retryWithPassword(...args),
+ unlockLocalDocument: (...args: unknown[]) => unlockLocalDocument(...args),
+ repairDocuments: (...args: unknown[]) => repairDocuments(...args),
+ retryWithFiles: (...args: unknown[]) => retryWithFiles(...args),
+}));
+
+const rerunPolicy = vi.fn();
+const rechainPolicyOnDocument = vi.fn();
+const canPlacePolicy = vi.fn();
+vi.mock("@app/services/notificationPolicyRetry", () => ({
+ canPlacePolicy: (...args: unknown[]) => canPlacePolicy(...args),
+ rerunPolicy: (...args: unknown[]) => rerunPolicy(...args),
+ rechainPolicyOnDocument: (...args: unknown[]) =>
+ rechainPolicyOnDocument(...args),
+}));
+
+const reportNotificationResolved = vi.fn();
+vi.mock("@app/services/notifications", async () => ({
+ ...(await vi.importActual<typeof import("@app/services/notifications")>(
+ "@app/services/notifications",
+ )),
+ reportNotificationResolved: (...args: unknown[]) =>
+ reportNotificationResolved(...args),
+}));
+
+const navigate = vi.fn();
+vi.mock("react-router-dom", async () => ({
+ ...(await vi.importActual<typeof import("react-router-dom")>(
+ "react-router-dom",
+ )),
+ useNavigate: () => navigate,
+}));
+
+// No i18n instance here, and the plugin is stubbed because the contexts below reach `core/i18n`.
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback: string) => fallback,
+ }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+
+// IndexedDB, which jsdom has none of. Answered here so presence is a fact of the test.
+const h = vi.hoisted(() => ({
+ stub: { id: "f-1" } as unknown,
+ getStirlingFileStub: vi.fn(),
+}));
+
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFileStub: (fileId: string) => h.getStirlingFileStub(fileId),
+ },
+}));
+
+const { FileActionsContext, FileStoreContext } =
+ await import("@app/contexts/file/contexts");
+const { NavigationActionsContext } =
+ await import("@app/contexts/NavigationContext");
+const { ViewerContext } = await import("@app/contexts/ViewerContext");
+const { useNotificationActions } =
+ await import("@app/components/notifications/notificationActions");
+
+const addStirlingFileStubs = vi.fn();
+const setActiveFileId = vi.fn();
+const setWorkbench = vi.fn();
+const setToolAndWorkbench = vi.fn();
+// createChildStub is stubbed too, so the test can name the version's id directly.
+vi.mock("@app/contexts/file/fileActions", () => ({
+ generateProcessedFileMetadata: () => Promise.resolve(null),
+ createChildStub: (parent: { id: string }, _op: unknown, file: File) => ({
+ ...parent,
+ id: "f-unlocked",
+ name: file.name,
+ versionNumber: 2,
+ parentFileId: parent.id,
+ }),
+}));
+
+/** What the workbench already holds, so the "do not add it twice" path can be exercised. */
+let openFileIds: string[] = [];
+/** Stubs the workbench holds, so the in-place replacement path has an original to version. */
+let openFilesById: Record<string, unknown> = {};
+const setSelectedFiles = vi.fn();
+const addFiles = vi.fn();
+const consumeFiles = vi.fn();
+
+/** The editor shell: the workbench's providers all sit above the bell. */
+const inEditor = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter>
+ <FileActionsContext.Provider
+ value={{
+ actions: {
+ addStirlingFileStubs,
+ setSelectedFiles,
+ addFiles,
+ consumeFiles,
+ } as never,
+ dispatch: vi.fn(),
+ }}
+ >
+ <FileStoreContext.Provider
+ value={
+ {
+ getState: () => ({
+ files: { ids: openFileIds, byId: openFilesById },
+ }),
+ subscribe: () => () => {},
+ selectors: {},
+ } as never
+ }
+ >
+ <NavigationActionsContext.Provider
+ value={{ actions: { setWorkbench, setToolAndWorkbench } } as never}
+ >
+ <ViewerContext.Provider value={{ setActiveFileId } as never}>
+ {children}
+ </ViewerContext.Provider>
+ </NavigationActionsContext.Provider>
+ </FileStoreContext.Provider>
+ </FileActionsContext.Provider>
+ </MemoryRouter>
+);
+
+function registry(wrapper = inEditor) {
+ return renderHook(() => useNotificationActions(), { wrapper }).result.current;
+}
+
+beforeEach(() => {
+ navigate.mockReset();
+ addStirlingFileStubs.mockReset().mockResolvedValue([]);
+ setActiveFileId.mockReset();
+ setWorkbench.mockReset();
+ setToolAndWorkbench.mockReset();
+ h.getStirlingFileStub.mockReset().mockResolvedValue(h.stub);
+ openFileIds = [];
+ openFilesById = {};
+ setSelectedFiles.mockReset();
+ consumeFiles.mockReset().mockResolvedValue(["f-unlocked"]);
+ // The adopted document's own id, not the reference the failure was filed against.
+ addFiles.mockReset().mockResolvedValue([{ fileId: "f-unlocked" }]);
+ reportNotificationResolved.mockReset().mockResolvedValue(true);
+ retryWithPassword.mockReset().mockResolvedValue({ ok: true, files: [] });
+ // The unlock succeeds by default: most cases below are about what happens afterwards.
+ unlockLocalDocument.mockReset().mockResolvedValue({
+ ok: true,
+ files: [
+ {
+ blob: new Blob(["pdf"], { type: "application/pdf" }),
+ filename: "invoice.pdf",
+ },
+ ],
+ });
+ // The repair succeeds by default: most cases below are about what happens afterwards.
+ repairDocuments.mockReset().mockResolvedValue({
+ ok: true,
+ repaired: [
+ {
+ fileId: "f-1",
+ file: {
+ blob: new Blob(["repaired"], { type: "application/pdf" }),
+ filename: "invoice_repaired.pdf",
+ },
+ },
+ ],
+ });
+ retryWithFiles.mockReset().mockResolvedValue({ ok: true, files: [] });
+ // Tracked by default: something is polling the run, so its output will arrive.
+ rerunPolicy.mockReset().mockResolvedValue({ ok: true, tracked: true });
+ rechainPolicyOnDocument.mockReset().mockResolvedValue({
+ ok: true,
+ tracked: true,
+ });
+ // Placeable by default: the browser still holds the policy the failure names.
+ canPlacePolicy.mockReset().mockReturnValue(true);
+ window.sessionStorage.clear();
+ window.history.pushState({}, "", "/");
+});
+
+/** Repair is decrypt's shape without the password: fix the input, then re-run what failed. */
+describe("REPAIR", () => {
+ it("repairs the document, then re-runs the policy that failed on it", async () => {
+ const outcome = await registry().REPAIR?.run(
+ policyContext({ kindId: "INPUT_CORRUPTED" }),
+ );
+
+ expect(repairDocuments).toHaveBeenCalledWith(["f-1"]);
+ // The re-run, not the repair, is what resolves the row.
+ expect(rechainPolicyOnDocument).toHaveBeenCalled();
+ expect(outcome).toEqual({ ok: true });
+ expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1");
+ });
+
+ it("is not offered when the policy cannot be placed, and spends nothing if pressed", async () => {
+ // The run would go to the server and bill, but nothing here could file it, so its output
+ // would never arrive and the row would stay open to be pressed again.
+ canPlacePolicy.mockReturnValue(false);
+ const row = policyContext({ kindId: "INPUT_CORRUPTED" });
+
+ expect(registry().REPAIR?.available?.(row)).toBe(false);
+
+ expect(await registry().REPAIR?.run(row)).toEqual({
+ ok: false,
+ message: "This document can no longer be retried from this browser.",
+ });
+ expect(repairDocuments).not.toHaveBeenCalled();
+ expect(rechainPolicyOnDocument).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" }),
+ );
+
+ expect(repairDocuments).toHaveBeenCalledWith(["f-1"]);
+ const [payload, files] = retryWithFiles.mock.calls[0] as [
+ { endpoint: string },
+ File[],
+ ];
+ expect(payload.endpoint).toBe("/api/v1/misc/compress-pdf");
+ expect(await bytesOf(files[0])).toBe("repaired");
+ expect(outcome).toEqual({ ok: true });
+ expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1");
+ // The repaired input is never versioned onto the original on a tool row: only what the
+ // re-run makes is kept, so the damaged document is left exactly as the user had it.
+ expect(consumeFiles).not.toHaveBeenCalled();
+ });
+
+ it("adopts the re-run's output and nothing else", async () => {
+ retryWithFiles.mockResolvedValue({
+ ok: true,
+ files: [
+ {
+ blob: new Blob(["smaller"], { type: "application/pdf" }),
+ filename: "invoice_compressed.pdf",
+ },
+ ],
+ });
+
+ await registry().REPAIR?.run(context({ kindId: "INPUT_CORRUPTED" }));
+
+ const [files, options] = addFiles.mock.calls[0];
+ expect((files as File[]).map((file) => file.name)).toEqual([
+ "invoice_compressed.pdf",
+ ]);
+ expect(options).toEqual({ selectFiles: true, derivedFromTool: true });
+ expect(addFiles).toHaveBeenCalledTimes(1);
+ expect(consumeFiles).not.toHaveBeenCalled();
+ });
+
+ it("is not offered when the stash lost a password, since that re-run would be a different one", async () => {
+ // Add Password on a damaged file: stashed without the password, a re-run would hand back an
+ // unprotected document and close the row as fixed.
+ const lostSecret = context({
+ kindId: "INPUT_CORRUPTED",
+ retryPayload: {
+ operation: "addPassword",
+ endpoint: "/api/v1/security/add-password",
+ params: {},
+ fileIds: ["f-1"],
+ multiFile: false,
+ errorCode: "E001",
+ replayUnfaithful: true,
+ recordedAt: 0,
+ },
+ });
+ const actions = registry();
+
+ expect(actions.REPAIR?.available(lostSecret)).toBe(false);
+ // The plain retry still opens the tool, where the password can be typed again.
+ expect(actions.OPEN_IN_TOOL?.available(lostSecret)).toBe(true);
+ expect(await actions.REPAIR?.run(lostSecret)).toEqual({
+ ok: false,
+ message: "This document can no longer be retried from this browser.",
+ });
+ expect(repairDocuments).not.toHaveBeenCalled();
+ });
+
+ it("repairs every input a merge would re-send, not just the one the row names", async () => {
+ // E002 is the multi-file corruption: re-running with one sibling still broken fails again.
+ repairDocuments.mockResolvedValue({
+ ok: true,
+ repaired: ["f-1", "f-2"].map((fileId) => ({
+ fileId,
+ file: { blob: new Blob(["repaired"]), filename: `${fileId}.pdf` },
+ })),
+ });
+
+ await registry().REPAIR?.run(
+ context({
+ kindId: "INPUT_CORRUPTED",
+ retryPayload: {
+ operation: "merge",
+ endpoint: "/api/v1/general/merge-pdfs",
+ params: {},
+ fileIds: ["f-1", "f-2"],
+ multiFile: true,
+ errorCode: "E002",
+ replayUnfaithful: false,
+ recordedAt: 0,
+ },
+ }),
+ );
+
+ expect(repairDocuments).toHaveBeenCalledWith(["f-1", "f-2"]);
+ // One re-run carrying both, which is the call that failed in the first place.
+ expect(retryWithFiles).toHaveBeenCalledTimes(1);
+ expect((retryWithFiles.mock.calls[0] as [unknown, File[]])[1]).toHaveLength(
+ 2,
+ );
+ // Repaired only to feed the re-run: the four siblings that were never damaged keep their
+ // originals rather than being swapped for Ghostscript's rewrite of them.
+ expect(consumeFiles).not.toHaveBeenCalled();
+ expect(addFiles).not.toHaveBeenCalled();
+ });
+
+ it("versions each repaired document under the original it came from", async () => {
+ openFilesById = { "f-1": { id: "f-1", name: "invoice.pdf" } };
+
+ await registry().REPAIR?.run(policyContext({ kindId: "INPUT_CORRUPTED" }));
+
+ // consumeFiles, not addFiles: the repaired copy replaces the original in the workbench.
+ expect(consumeFiles).toHaveBeenCalledWith(
+ ["f-1"],
+ expect.anything(),
+ expect.anything(),
+ );
+ expect(addFiles).not.toHaveBeenCalled();
+ });
+
+ it("stops at a failed repair, leaving the row open with the server's words", async () => {
+ repairDocuments.mockResolvedValue({
+ ok: false,
+ reason: "serverMessage",
+ message: "Repair failed with available tools.",
+ });
+
+ const outcome = await registry().REPAIR?.run(
+ policyContext({ kindId: "INPUT_CORRUPTED" }),
+ );
+
+ expect(outcome).toEqual({
+ ok: false,
+ message: "Repair failed with available tools.",
+ });
+ expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
+ it("leaves the row open when the repair worked but the re-run failed again", async () => {
+ retryWithFiles.mockResolvedValue({
+ ok: false,
+ reason: "serverMessage",
+ message: "PDF file appears to be corrupted or damaged.",
+ });
+
+ const outcome = await registry().REPAIR?.run(
+ context({ kindId: "INPUT_CORRUPTED" }),
+ );
+
+ expect(outcome).toEqual({
+ ok: false,
+ message: "PDF file appears to be corrupted or damaged.",
+ });
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ // And the workbench is untouched, so pressing again changes nothing rather than adding a
+ // second repaired copy each time.
+ expect(consumeFiles).not.toHaveBeenCalled();
+ expect(addFiles).not.toHaveBeenCalled();
+ });
+
+ it("leaves the row open when the policy re-run cannot be tracked", async () => {
+ rechainPolicyOnDocument.mockResolvedValue({ ok: true, tracked: false });
+
+ const outcome = await registry().REPAIR?.run(
+ policyContext({ kindId: "INPUT_CORRUPTED" }),
+ );
+
+ expect(outcome?.ok).toBe(false);
+ expect(outcome?.message).toContain("repaired");
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
+ it("is offered only where the repaired document has somewhere to land", async () => {
+ expect(
+ registry().REPAIR?.available(
+ policyContext({ kindId: "INPUT_CORRUPTED" }),
+ ),
+ ).toBe(true);
+ // Without a workbench the row promotes the next action instead.
+ expect(
+ registry(inProcessor).REPAIR?.available(
+ policyContext({ kindId: "INPUT_CORRUPTED" }),
+ ),
+ ).toBe(false);
+ });
+
+ it("is not offered once the document has left this browser", async () => {
+ expect(
+ registry().REPAIR?.available(
+ context({ kindId: "INPUT_CORRUPTED", hasLocalFile: false }),
+ ),
+ ).toBe(false);
+ });
+
+ it("is not offered for a stash belonging to a different failure on the same file", async () => {
+ // The stash on this file belongs to the E004 row, not this one.
+ expect(
+ registry().REPAIR?.available(
+ context({
+ kindId: "INPUT_CORRUPTED",
+ retryPayload: {
+ operation: "removePassword",
+ endpoint: "/api/v1/security/remove-password",
+ params: {},
+ fileIds: ["f-1"],
+ multiFile: false,
+ errorCode: "E004",
+ replayUnfaithful: false,
+ recordedAt: 0,
+ },
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("never asks for a password, having nothing to do with one", async () => {
+ expect(registry().REPAIR?.needsPassword).toBeFalsy();
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/repair.ts b/frontend/editor/src/proprietary/components/notifications/resolutions/repair.ts
new file mode 100644
index 0000000000..6103b86171
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/repair.ts
@@ -0,0 +1,59 @@
+import {
+ repairDocuments,
+ retryInputIds,
+ retryWithFiles,
+} from "@app/services/notificationRetry";
+import type { FileId } from "@app/types/file";
+import {
+ asFile,
+ type Resolution,
+} from "@app/components/notifications/resolutions/resolution";
+
+export const repair: Resolution = {
+ actionId: "REPAIR",
+ toolId: "repair",
+ needsPassword: false,
+ async produce(target, context) {
+ // Every input the re-run will send, so a merge cannot fail again on an unrepaired sibling.
+ const originalIds =
+ target.kind === "tool"
+ ? retryInputIds(target.payload, context.notification.fileId)
+ : [target.policy.fileId];
+
+ const outcome = await repairDocuments(originalIds);
+ if (!outcome.ok) return outcome;
+
+ // Paired to its original: a policy row versions that in place, while a tool row only feeds
+ // these into the re-run and keeps the output.
+ return {
+ ok: true,
+ produced: (outcome.repaired ?? []).map((document) => ({
+ file: asFile(document.file),
+ originalId: document.fileId as FileId,
+ })),
+ };
+ },
+ toolRerun: {
+ run: (payload, files) => retryWithFiles(payload, files),
+ notAdopted: (t) =>
+ t(
+ "notifications.repairedRerunNotAdopted",
+ "The repaired document went through, but its result could not be opened here.",
+ ),
+ },
+ adoptFailed: (t) =>
+ t(
+ "notifications.repairAdoptFailed",
+ "The document was repaired but could not be opened here. Try the Repair tool directly.",
+ ),
+ notRerun: (t) =>
+ t(
+ "notifications.repairedNotRerun",
+ "The document was repaired and opened here, but the policy could not be run on it again.",
+ ),
+ rerunUndelivered: (t) =>
+ t(
+ "notifications.repairedRerunUndelivered",
+ "The document was repaired and the policy re-run started, but its result cannot be delivered here, so this failure stays open.",
+ ),
+};
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/resolution.ts b/frontend/editor/src/proprietary/components/notifications/resolutions/resolution.ts
new file mode 100644
index 0000000000..de8f15bbc2
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/resolution.ts
@@ -0,0 +1,346 @@
+import type { ContextType } from "react";
+import type { useTranslation } from "react-i18next";
+import type {
+ FileActionsContext,
+ FileStoreContext,
+} from "@app/contexts/file/contexts";
+import { fileStorage } from "@app/services/fileStorage";
+import {
+ clearRetryPayload,
+ stashMatchesKind,
+ type RetryFailure,
+ type RetryOutcome,
+ type RetryOutputFile,
+ type RetryPayload,
+} from "@app/services/notificationRetry";
+import {
+ canPlacePolicy,
+ rechainPolicyOnDocument,
+ type PolicyRerunOutcome,
+ type PolicyRetryTarget,
+} from "@app/services/notificationPolicyRetry";
+import { reportNotificationResolved } from "@app/services/notifications";
+import type { FileId } from "@app/types/file";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import { isValidToolId, type ToolId } from "@app/types/toolId";
+import type {
+ ClientActionOutcome,
+ ClientActionSpec,
+ NotificationActionContext,
+} from "@app/components/notifications/notificationActions";
+import {
+ addToWorkbench,
+ versionUnder,
+} from "@app/components/notifications/resolutions/adopt";
+
+// A resolution is decrypt's shape with the fix swapped out: produce a fixed document, take it
+// into the workbench, re-run what failed, then tell the server. The differences between fixes
+// are data, so the skeleton is written once and each fix supplies only what it does differently.
+
+export type Translate = ReturnType<typeof useTranslation>["t"];
+
+export type ResolutionActionId = "DECRYPT" | "REPAIR";
+
+/** A tool retry is an endpoint plus client-held parameters; a policy retry is a stored pair. */
+export type RetryTarget =
+ | { readonly kind: "tool"; readonly payload: RetryPayload }
+ | { readonly kind: "policy"; readonly policy: PolicyRetryTarget };
+
+/** A document a fix produced, and the original to version it under, or null to add it instead. */
+export interface ProducedDocument {
+ file: File;
+ originalId: FileId | null;
+}
+
+/** As {@link RetryOutcome}, with the outputs paired to what they replace. */
+export interface ProduceOutcome {
+ ok: boolean;
+ reason?: RetryFailure;
+ message?: string | null;
+ produced?: ProducedDocument[];
+}
+
+/** The tool-origin second half: re-run the stashed operation over what the fix produced. */
+export interface ToolRerun {
+ run(payload: RetryPayload, files: File[]): Promise<RetryOutcome>;
+ notAdopted(t: Translate): string;
+}
+
+export interface Resolution {
+ actionId: ResolutionActionId;
+ /** The tool whose manual run counts as this resolution too. */
+ toolId: ToolId;
+ needsPassword: boolean;
+ produce(
+ target: RetryTarget,
+ context: NotificationActionContext,
+ password?: string,
+ ): Promise<ProduceOutcome>;
+ /** Absent when `produce` already re-ran the failed operation, as an unlock does. */
+ toolRerun?: ToolRerun;
+ adoptFailed(t: Translate): string;
+ notRerun(t: Translate): string;
+ rerunUndelivered(t: Translate): string;
+}
+
+export interface ResolutionDeps {
+ t: Translate;
+ fileContext: ContextType<typeof FileActionsContext>;
+ fileStore: ContextType<typeof FileStoreContext>;
+}
+
+/** Which of the two a notification describes, or null when nothing here can re-run it. */
+export function retryTargetOf(
+ context: NotificationActionContext,
+): RetryTarget | null {
+ const { notification, hasLocalFile, retryPayload } = context;
+ if (!hasLocalFile) return null;
+
+ // The policy shape wins where it applies, being the more specific claim.
+ const attended = (notification.sourceId ?? null) === null;
+ if (attended && notification.policyId && notification.fileId) {
+ // No target at all when the policy cannot be placed, rather than one that submits a run
+ // whose output never arrives: the row would stay open and bill again on the next press.
+ return canPlacePolicy(notification.policyId)
+ ? {
+ kind: "policy",
+ policy: {
+ policyId: notification.policyId,
+ fileId: notification.fileId,
+ },
+ }
+ : null;
+ }
+
+ // One stash per file, but one incident per kind per file, so the stash may be another row's.
+ return retryPayload && stashMatchesKind(notification.kindId, retryPayload)
+ ? { kind: "tool", payload: retryPayload }
+ : null;
+}
+
+/** A policy re-run also needs the editor's providers, to collect its output. */
+export function canRetry(
+ context: NotificationActionContext,
+ fileContext: ContextType<typeof FileActionsContext>,
+): boolean {
+ const target = retryTargetOf(context);
+ if (!target) return false;
+ return target.kind === "tool" || fileContext !== undefined;
+}
+
+/**
+ * A stash that cannot reproduce the run it describes, because a secret was dropped from it or
+ * because the tool exposes no mapping to its request body. Re-running it would produce a file
+ * from different settings and then call the row fixed. Such a row keeps its plain retry, which
+ * opens the tool and lets the reader see the settings first.
+ */
+function toolRerunWouldBeWrong(
+ resolution: Resolution,
+ target: RetryTarget | null,
+): boolean {
+ return (
+ target?.kind === "tool" &&
+ resolution.toolRerun !== undefined &&
+ target.payload.replayUnfaithful
+ );
+}
+
+/** The stashed `params` stay stashed: `useBaseParameters` has no seam for initial values. */
+export function toolOf(payload: RetryPayload): ToolId | null {
+ return isValidToolId(payload.operation) ? payload.operation : null;
+}
+
+export function asFile(output: RetryOutputFile): File {
+ return new File([output.blob], output.filename, {
+ type: output.blob.type || "application/pdf",
+ });
+}
+
+export function asFiles(outputs: RetryOutputFile[]): File[] {
+ return outputs.map(asFile);
+}
+
+export function unavailable(t: Translate): ClientActionOutcome {
+ return {
+ ok: false,
+ message: t(
+ "notifications.retryUnavailable",
+ "This document can no longer be retried from this browser.",
+ ),
+ };
+}
+
+/** The service reports why and this layer words it, because the wording belongs where `t` is. */
+function retryFailure(
+ t: Translate,
+ outcome: RetryOutcome | ProduceOutcome,
+): ClientActionOutcome {
+ if (outcome.reason === "fileMissing") {
+ return {
+ ok: false,
+ message: t(
+ "notifications.notOnThisDevice",
+ "This document is not on this device, so it cannot be opened or retried here.",
+ ),
+ };
+ }
+ if (outcome.reason === "notRetryable") return unavailable(t);
+ // The server's own words, or nothing: the row falls back to its generic failure line.
+ return { ok: false, message: outcome.message ?? undefined };
+}
+
+/**
+ * An untracked run is a failure on purpose: nothing here will collect what it produces. With a
+ * `resolution` the copy names what already happened to the document, because the user is left
+ * holding it either way; without one it is a plain re-run.
+ */
+export function rerunOutcome(
+ t: Translate,
+ outcome: PolicyRerunOutcome,
+ resolution: Resolution | null,
+): ClientActionOutcome {
+ if (outcome.ok && outcome.tracked) return { ok: true };
+ if (outcome.ok) {
+ return {
+ ok: false,
+ message: resolution
+ ? resolution.rerunUndelivered(t)
+ : t(
+ "notifications.rerunUndelivered",
+ "The policy re-run started, but its result cannot be delivered here, so this failure stays open.",
+ ),
+ };
+ }
+ if (outcome.reason === "missingFile") {
+ return {
+ ok: false,
+ message: t(
+ "notifications.notOnThisDevice",
+ "This document is not on this device, so it cannot be opened or retried here.",
+ ),
+ };
+ }
+ if (resolution) return { ok: false, message: resolution.notRerun(t) };
+ return {
+ ok: false,
+ message:
+ outcome.message ??
+ t(
+ "notifications.rerunRejected",
+ "The policy could not be run again just now. Try again in a moment.",
+ ),
+ };
+}
+
+/** Storage too, or a file merely closed in the sidebar gets a copy rather than a version. */
+async function parentStubFor(
+ fileStore: ContextType<typeof FileStoreContext>,
+ fileId: FileId,
+): Promise<StirlingFileStub | null> {
+ return (
+ fileStore?.getState().files.byId?.[fileId] ??
+ (await fileStorage.getStirlingFileStub(fileId)) ??
+ null
+ );
+}
+
+export function resolutionSpec(
+ resolution: Resolution,
+ { t, fileContext, fileStore }: ResolutionDeps,
+): ClientActionSpec {
+ /** Versioned under its original where that is still held here, added on its own otherwise. */
+ const take = async (
+ actions: NonNullable<typeof fileContext>["actions"],
+ document: ProducedDocument,
+ ): Promise<FileId[]> => {
+ const parent = document.originalId
+ ? await parentStubFor(fileStore, document.originalId)
+ : null;
+ return parent
+ ? versionUnder(actions, parent, document.file, resolution.toolId)
+ : addToWorkbench(actions, document.file);
+ };
+
+ return {
+ // A produced document needs somewhere to land, so the processor shell promotes past this.
+ available: (context) =>
+ fileContext !== undefined &&
+ canRetry(context, fileContext) &&
+ !toolRerunWouldBeWrong(resolution, retryTargetOf(context)),
+ needsPassword: resolution.needsPassword,
+ // On success the adopted document is the destination, and it is behind the panel.
+ closesPanel: true,
+ run: async (context, password): Promise<ClientActionOutcome> => {
+ const target = retryTargetOf(context);
+ if (
+ !target ||
+ (resolution.needsPassword && !password) ||
+ !fileContext ||
+ toolRerunWouldBeWrong(resolution, target)
+ ) {
+ return unavailable(t);
+ }
+
+ const outcome = await resolution.produce(target, context, password);
+ if (!outcome.ok) return retryFailure(t, outcome);
+ const produced = outcome.produced ?? [];
+
+ if (target.kind === "policy") {
+ // A failed adoption fails the action: dropping the result leaves them nothing.
+ const adopted: FileId[] = [];
+ try {
+ for (const document of produced) {
+ adopted.push(...(await take(fileContext.actions, document)));
+ }
+ } catch {
+ return { ok: false, message: resolution.adoptFailed(t) };
+ }
+
+ // Under the ORIGINAL reference so a repeat folds on, and after the adoption.
+ const document = produced[0];
+ const rerun: PolicyRerunOutcome = document
+ ? await rechainPolicyOnDocument(
+ target.policy,
+ document.file,
+ adopted[0] ?? null,
+ )
+ : { ok: false, reason: "missingFile" };
+ // Anything short of a tracked run stops here: the input alone is not the result.
+ const result = rerunOutcome(t, rerun, resolution);
+ if (!result.ok) return result;
+ } else if (resolution.toolRerun) {
+ // Nothing is adopted until the re-run has passed. A repaired input that still fails
+ // would otherwise replace the original, and every further press would add another.
+ const rerun = await resolution.toolRerun.run(
+ target.payload,
+ produced.map((document) => document.file),
+ );
+ if (!rerun.ok) return retryFailure(t, rerun);
+ // Only the output, and added rather than versioned: the originals stay as they were. A
+ // merge repairs every input to re-run at all, but the siblings that were never damaged
+ // must not be swapped for rewritten copies.
+ try {
+ for (const file of asFiles(rerun.files ?? [])) {
+ await addToWorkbench(fileContext.actions, file);
+ }
+ } catch {
+ return { ok: false, message: resolution.toolRerun.notAdopted(t) };
+ }
+ } else {
+ // `produce` already re-ran the operation, so what it made is the result.
+ try {
+ for (const document of produced)
+ await take(fileContext.actions, document);
+ } catch {
+ return { ok: false, message: resolution.adoptFailed(t) };
+ }
+ }
+
+ // Ignored on purpose: a refused resolve is not a failed fix.
+ await reportNotificationResolved(context.notification.id);
+ // The stash described the run that just succeeded, so it has nothing left to offer.
+ await clearRetryPayload(context.notification.fileId);
+ return { ok: true };
+ },
+ };
+}
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/testSupport.tsx b/frontend/editor/src/proprietary/components/notifications/resolutions/testSupport.tsx
new file mode 100644
index 0000000000..91e74b37c9
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/testSupport.tsx
@@ -0,0 +1,123 @@
+import type { ReactNode } from "react";
+import { MemoryRouter } from "react-router-dom";
+import type { NotificationActionContext } from "@app/components/notifications/notificationActions";
+import type {
+ AppNotification,
+ NotificationActionOffer,
+} from "@app/services/notifications";
+import type { RetryPayload } from "@app/services/notificationRetry";
+
+// Fixtures shared by the registry test and each resolution's own. The mocks stay in the test
+// files: vi.mock is hoisted per file, so a helper cannot own them.
+
+export function notification(
+ overrides: Partial<AppNotification> = {},
+): AppNotification {
+ return {
+ id: "failure:evt-1",
+ source: "FAILURE",
+ kindId: "INPUT_PASSWORD_PROTECTED",
+ origin: "TOOL",
+ ownership: "MINE",
+ severity: "ERROR",
+ status: "NEW",
+ titleKey: "portal.failures.kind.inputPasswordProtected.title",
+ defaultTitle: "Password-protected document",
+ detail: "The PDF Document is passworded",
+ fileId: "f-1",
+ sourceId: null,
+ policyId: null,
+ occurrences: 3,
+ createdAt: "2026-08-06T00:00:00Z",
+ lastSeenAt: "2026-08-06T00:00:00Z",
+ actions: [],
+ ...overrides,
+ };
+}
+
+export function offer(id: string): NotificationActionOffer {
+ return {
+ id,
+ labelKey: `portal.failures.action.${id.toLowerCase()}`,
+ defaultLabel: id,
+ slot: "SECONDARY",
+ enabled: true,
+ disabledReasonKey: null,
+ };
+}
+
+/** The stash a failure of `kindId` would have left: the operation that failed, with its code. */
+function payloadFor(kindId: string): RetryPayload {
+ if (kindId === "INPUT_CORRUPTED") {
+ return {
+ operation: "compress",
+ endpoint: "/api/v1/misc/compress-pdf",
+ params: { level: "5" },
+ fileIds: ["f-1"],
+ multiFile: false,
+ errorCode: "E001",
+ replayUnfaithful: false,
+ recordedAt: 0,
+ };
+ }
+ return {
+ operation: "removePassword",
+ endpoint: "/api/v1/security/remove-password",
+ params: {},
+ fileIds: ["f-1"],
+ multiFile: false,
+ errorCode: "E004",
+ replayUnfaithful: false,
+ recordedAt: 0,
+ };
+}
+
+export interface ContextOverrides extends Partial<NotificationActionContext> {
+ kindId?: string;
+}
+
+/** A tool failure the server classified as `kindId`, with its stash still here. */
+export function context({
+ kindId = "INPUT_PASSWORD_PROTECTED",
+ ...overrides
+}: ContextOverrides = {}): NotificationActionContext {
+ return {
+ notification: notification({ kindId }),
+ hasLocalFile: true,
+ retryPayload: payloadFor(kindId),
+ ...overrides,
+ };
+}
+
+/** An attended policy run: the row names the policy and the document, and nothing was stashed. */
+export function policyContext({
+ kindId = "INPUT_PASSWORD_PROTECTED",
+ ...overrides
+}: ContextOverrides = {}): NotificationActionContext {
+ return {
+ notification: notification({
+ kindId,
+ origin: "POLICY",
+ policyId: "pol-1",
+ sourceId: null,
+ }),
+ hasLocalFile: true,
+ retryPayload: null,
+ ...overrides,
+ };
+}
+
+/** The processor shell: the portal mounts above the app's providers, so there is none. */
+export const inProcessor = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter>{children}</MemoryRouter>
+);
+
+/** A file's own bytes. Via FileReader because this environment's Blob has no `text`. */
+export function bytesOf(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(file);
+ });
+}
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/unlock.test.tsx b/frontend/editor/src/proprietary/components/notifications/resolutions/unlock.test.tsx
new file mode 100644
index 0000000000..ff5ed3f2c7
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/unlock.test.tsx
@@ -0,0 +1,497 @@
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import {
+ bytesOf,
+ context,
+ policyContext,
+} from "@app/components/notifications/resolutions/testSupport";
+
+// Where each action sends the reader. Only the editor has the workbench contexts above it.
+
+const retryWithPassword = vi.fn();
+const unlockLocalDocument = vi.fn();
+const repairDocuments = vi.fn();
+const retryWithFiles = vi.fn();
+vi.mock("@app/services/notificationRetry", async (importOriginal) => ({
+ // The real stashMatchesKind and retryInputIds: both are pure, and their guards are part of
+ // what these tests exercise.
+ ...(await importOriginal<typeof import("@app/services/notificationRetry")>()),
+ retryWithPassword: (...args: unknown[]) => retryWithPassword(...args),
+ unlockLocalDocument: (...args: unknown[]) => unlockLocalDocument(...args),
+ repairDocuments: (...args: unknown[]) => repairDocuments(...args),
+ retryWithFiles: (...args: unknown[]) => retryWithFiles(...args),
+}));
+
+const rerunPolicy = vi.fn();
+const rechainPolicyOnDocument = vi.fn();
+const canPlacePolicy = vi.fn();
+vi.mock("@app/services/notificationPolicyRetry", () => ({
+ canPlacePolicy: (...args: unknown[]) => canPlacePolicy(...args),
+ rerunPolicy: (...args: unknown[]) => rerunPolicy(...args),
+ rechainPolicyOnDocument: (...args: unknown[]) =>
+ rechainPolicyOnDocument(...args),
+}));
+
+const reportNotificationResolved = vi.fn();
+vi.mock("@app/services/notifications", async () => ({
+ ...(await vi.importActual<typeof import("@app/services/notifications")>(
+ "@app/services/notifications",
+ )),
+ reportNotificationResolved: (...args: unknown[]) =>
+ reportNotificationResolved(...args),
+}));
+
+const navigate = vi.fn();
+vi.mock("react-router-dom", async () => ({
+ ...(await vi.importActual<typeof import("react-router-dom")>(
+ "react-router-dom",
+ )),
+ useNavigate: () => navigate,
+}));
+
+// No i18n instance here, and the plugin is stubbed because the contexts below reach `core/i18n`.
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback: string) => fallback,
+ }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+
+// IndexedDB, which jsdom has none of. Answered here so presence is a fact of the test.
+const h = vi.hoisted(() => ({
+ stub: { id: "f-1" } as unknown,
+ getStirlingFileStub: vi.fn(),
+}));
+
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFileStub: (fileId: string) => h.getStirlingFileStub(fileId),
+ },
+}));
+
+const { FileActionsContext, FileStoreContext } =
+ await import("@app/contexts/file/contexts");
+const { NavigationActionsContext } =
+ await import("@app/contexts/NavigationContext");
+const { ViewerContext } = await import("@app/contexts/ViewerContext");
+const { useNotificationActions } =
+ await import("@app/components/notifications/notificationActions");
+
+const addStirlingFileStubs = vi.fn();
+const setActiveFileId = vi.fn();
+const setWorkbench = vi.fn();
+const setToolAndWorkbench = vi.fn();
+// createChildStub is stubbed too, so the test can name the version's id directly.
+vi.mock("@app/contexts/file/fileActions", () => ({
+ generateProcessedFileMetadata: () => Promise.resolve(null),
+ createChildStub: (parent: { id: string }, _op: unknown, file: File) => ({
+ ...parent,
+ id: "f-unlocked",
+ name: file.name,
+ versionNumber: 2,
+ parentFileId: parent.id,
+ }),
+}));
+
+/** What the workbench already holds, so the "do not add it twice" path can be exercised. */
+let openFileIds: string[] = [];
+/** Stubs the workbench holds, so the in-place replacement path has an original to version. */
+let openFilesById: Record<string, unknown> = {};
+const setSelectedFiles = vi.fn();
+const addFiles = vi.fn();
+const consumeFiles = vi.fn();
+
+/** The editor shell: the workbench's providers all sit above the bell. */
+const inEditor = ({ children }: { children: ReactNode }) => (
+ <MemoryRouter>
+ <FileActionsContext.Provider
+ value={{
+ actions: {
+ addStirlingFileStubs,
+ setSelectedFiles,
+ addFiles,
+ consumeFiles,
+ } as never,
+ dispatch: vi.fn(),
+ }}
+ >
+ <FileStoreContext.Provider
+ value={
+ {
+ getState: () => ({
+ files: { ids: openFileIds, byId: openFilesById },
+ }),
+ subscribe: () => () => {},
+ selectors: {},
+ } as never
+ }
+ >
+ <NavigationActionsContext.Provider
+ value={{ actions: { setWorkbench, setToolAndWorkbench } } as never}
+ >
+ <ViewerContext.Provider value={{ setActiveFileId } as never}>
+ {children}
+ </ViewerContext.Provider>
+ </NavigationActionsContext.Provider>
+ </FileStoreContext.Provider>
+ </FileActionsContext.Provider>
+ </MemoryRouter>
+);
+
+function registry(wrapper = inEditor) {
+ return renderHook(() => useNotificationActions(), { wrapper }).result.current;
+}
+
+beforeEach(() => {
+ navigate.mockReset();
+ addStirlingFileStubs.mockReset().mockResolvedValue([]);
+ setActiveFileId.mockReset();
+ setWorkbench.mockReset();
+ setToolAndWorkbench.mockReset();
+ h.getStirlingFileStub.mockReset().mockResolvedValue(h.stub);
+ openFileIds = [];
+ openFilesById = {};
+ setSelectedFiles.mockReset();
+ consumeFiles.mockReset().mockResolvedValue(["f-unlocked"]);
+ // The adopted document's own id, not the reference the failure was filed against.
+ addFiles.mockReset().mockResolvedValue([{ fileId: "f-unlocked" }]);
+ reportNotificationResolved.mockReset().mockResolvedValue(true);
+ retryWithPassword.mockReset().mockResolvedValue({ ok: true, files: [] });
+ // The unlock succeeds by default: most cases below are about what happens afterwards.
+ unlockLocalDocument.mockReset().mockResolvedValue({
+ ok: true,
+ files: [
+ {
+ blob: new Blob(["pdf"], { type: "application/pdf" }),
+ filename: "invoice.pdf",
+ },
+ ],
+ });
+ // The repair succeeds by default: most cases below are about what happens afterwards.
+ repairDocuments.mockReset().mockResolvedValue({
+ ok: true,
+ repaired: [
+ {
+ fileId: "f-1",
+ file: {
+ blob: new Blob(["repaired"], { type: "application/pdf" }),
+ filename: "invoice_repaired.pdf",
+ },
+ },
+ ],
+ });
+ retryWithFiles.mockReset().mockResolvedValue({ ok: true, files: [] });
+ // Tracked by default: something is polling the run, so its output will arrive.
+ rerunPolicy.mockReset().mockResolvedValue({ ok: true, tracked: true });
+ rechainPolicyOnDocument.mockReset().mockResolvedValue({
+ ok: true,
+ tracked: true,
+ });
+ // Placeable by default: the browser still holds the policy the failure names.
+ canPlacePolicy.mockReset().mockReturnValue(true);
+ window.sessionStorage.clear();
+ window.history.pushState({}, "", "/");
+});
+
+describe("DECRYPT", () => {
+ it("unlocks with the password it was given and reports what came back", async () => {
+ retryWithPassword.mockResolvedValue({ ok: false, message: "Wrong" });
+
+ const outcome = await registry().DECRYPT?.run(context(), "hunter2");
+
+ expect(retryWithPassword).toHaveBeenCalledWith(
+ expect.objectContaining({ endpoint: "/api/v1/security/remove-password" }),
+ "hunter2",
+ // The row's own document, so a single-file endpoint is not handed the whole batch.
+ "f-1",
+ );
+ expect(outcome).toEqual({ ok: false, message: "Wrong" });
+ });
+
+ it("takes the unlocked document into the workbench through FileContext", async () => {
+ // The whole point of the password: the user must end up holding the unlocked file.
+ retryWithPassword.mockResolvedValue({
+ ok: true,
+ files: [
+ {
+ blob: new Blob(["pdf"], { type: "application/pdf" }),
+ filename: "invoice.pdf",
+ },
+ ],
+ });
+
+ const outcome = await registry().DECRYPT?.run(context(), "hunter2");
+
+ expect(outcome).toEqual({ ok: true });
+ const [files, options] = addFiles.mock.calls[0];
+ expect((files as File[]).map((file) => file.name)).toEqual(["invoice.pdf"]);
+ // Selected so it is on screen, and marked in-app so `usePolicyAutoRun` leaves it alone.
+ expect(options).toEqual({ selectFiles: true, derivedFromTool: true });
+ // And closed with the prefixed id: nothing else tells the server the client fixed it.
+ expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1");
+ });
+
+ it("replaces the encrypted original in place when it is open in the workbench", async () => {
+ // The failed document is on screen, so the unlock versions it rather than adding a second copy.
+ openFileIds = ["f-1"];
+ openFilesById = {
+ "f-1": { id: "f-1", name: "invoice.pdf", versionNumber: 1 },
+ };
+ unlockLocalDocument.mockResolvedValue({
+ ok: true,
+ files: [
+ {
+ blob: new Blob(["pdf"], { type: "application/pdf" }),
+ filename: "invoice.pdf",
+ },
+ ],
+ });
+
+ const outcome = await registry().DECRYPT?.run(policyContext(), "hunter2");
+
+ expect(outcome).toEqual({ ok: true });
+ // Consumed, not added: the encrypted original is versioned, so there is only ever one document.
+ expect(addFiles).not.toHaveBeenCalled();
+ const [inputIds, , stubs] = consumeFiles.mock.calls[0];
+ expect(inputIds).toEqual(["f-1"]);
+ // Still in-app, so usePolicyAutoRun does not enforce the chain on it — the rechain does that.
+ expect(
+ (stubs as Array<{ derivedFromTool?: boolean }>)[0].derivedFromTool,
+ ).toBe(true);
+ });
+
+ it("versions a document the workbench has closed, rather than adding a copy of it", async () => {
+ // Closed in the sidebar but still on the device: adding here left the user holding both.
+ openFileIds = [];
+ openFilesById = {};
+
+ await registry().DECRYPT?.run(policyContext(), "hunter2");
+
+ expect(addFiles).not.toHaveBeenCalled();
+ expect(consumeFiles.mock.calls[0][0]).toEqual(["f-1"]);
+ });
+
+ it("adds the unlocked document when nothing on this device holds the original", async () => {
+ // No stub anywhere: there is no version chain to extend, so adding is all that is left.
+ h.getStirlingFileStub.mockResolvedValue(null);
+
+ await registry().DECRYPT?.run(policyContext(), "hunter2");
+
+ expect(consumeFiles).not.toHaveBeenCalled();
+ expect(addFiles.mock.calls[0][1]).toEqual({
+ selectFiles: true,
+ derivedFromTool: true,
+ });
+ });
+
+ it("closes the incident only once the document is safely in", async () => {
+ // Reported first, then a failed adoption, would leave the row closed with nothing to show.
+ retryWithPassword.mockResolvedValue({
+ ok: true,
+ files: [{ blob: new Blob(["pdf"]), filename: "invoice.pdf" }],
+ });
+ addFiles.mockRejectedValue(new Error("quota"));
+
+ await registry().DECRYPT?.run(context(), "hunter2");
+
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
+ it("keeps the unlock a success when the server will not record it", async () => {
+ // The document is already in the workbench, so a refused resolve is not a failed unlock.
+ retryWithPassword.mockResolvedValue({
+ ok: true,
+ files: [{ blob: new Blob(["pdf"]), filename: "invoice.pdf" }],
+ });
+ reportNotificationResolved.mockResolvedValue(false);
+
+ expect(await registry().DECRYPT?.run(context(), "hunter2")).toEqual({
+ ok: true,
+ });
+ });
+
+ it("reports a failure when the unlocked document cannot be taken in", async () => {
+ // Unlocked but dropped leaves the user with nothing, so it is never reported as success.
+ retryWithPassword.mockResolvedValue({
+ ok: true,
+ files: [{ blob: new Blob(["pdf"]), filename: "invoice.pdf" }],
+ });
+ addFiles.mockRejectedValue(new Error("quota"));
+
+ const outcome = await registry().DECRYPT?.run(context(), "hunter2");
+
+ expect(outcome).toEqual({
+ ok: false,
+ message:
+ "The document was unlocked but could not be opened here. Try the tool directly.",
+ });
+ });
+
+ it("offers the unlock where the editor can take the result", () => {
+ expect(registry().DECRYPT?.available(context())).toBe(true);
+ expect(
+ registry().DECRYPT?.available(context({ hasLocalFile: false })),
+ ).toBe(false);
+ });
+
+ it("says so rather than posting nothing when the stash has gone", async () => {
+ const outcome = await registry().DECRYPT?.run(
+ context({ retryPayload: null }),
+ "hunter2",
+ );
+
+ expect(retryWithPassword).not.toHaveBeenCalled();
+ expect(outcome).toEqual({
+ ok: false,
+ message: "This document can no longer be retried from this browser.",
+ });
+ });
+});
+
+describe("DECRYPT on an attended policy run", () => {
+ it("unlocks, takes the document in, runs the policy again, then closes the incident", async () => {
+ const order: string[] = [];
+ consumeFiles.mockImplementation(async () => {
+ order.push("adopt");
+ return ["f-unlocked"];
+ });
+ rechainPolicyOnDocument.mockImplementation(async () => {
+ order.push("rerun");
+ return { ok: true, tracked: true };
+ });
+ reportNotificationResolved.mockImplementation(async () => {
+ order.push("resolve");
+ return true;
+ });
+
+ const outcome = await registry().DECRYPT?.run(policyContext(), "hunter2");
+
+ expect(outcome).toEqual({ ok: true });
+ // The unlock is the remove-password call on the document the row names, not a stashed endpoint.
+ expect(unlockLocalDocument).toHaveBeenCalledWith("f-1", "hunter2");
+ // Versioned onto the encrypted original, so there is one document rather than two.
+ expect(addFiles).not.toHaveBeenCalled();
+ const [inputIds, files, stubs] = consumeFiles.mock.calls[0];
+ expect(inputIds).toEqual(["f-1"]);
+ expect((files as File[]).map((file) => file.name)).toEqual(["invoice.pdf"]);
+ // derivedFromTool stops the adoption starting a SECOND, billed run of this same policy.
+ expect(
+ (stubs as Array<{ derivedFromTool?: boolean }>)[0].derivedFromTool,
+ ).toBe(true);
+ // Under the ORIGINAL reference so a repeat folds on, with the output on the ADOPTED document.
+ expect(rechainPolicyOnDocument).toHaveBeenCalledWith(
+ { policyId: "pol-1", fileId: "f-1" },
+ expect.any(File),
+ "f-unlocked",
+ );
+ // And with the prefixed notification id, never a raw failure id.
+ expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1");
+ expect(order).toEqual(["adopt", "rerun", "resolve"]);
+ });
+
+ it("starts exactly one run for one click", async () => {
+ await registry().DECRYPT?.run(policyContext(), "hunter2");
+
+ // One submission: the adoption's is silenced by derivedFromTool above.
+ expect(rechainPolicyOnDocument).toHaveBeenCalledTimes(1);
+ expect(rerunPolicy).not.toHaveBeenCalled();
+ expect(consumeFiles.mock.calls[0][2][0]).toMatchObject({
+ derivedFromTool: true,
+ });
+ });
+
+ it("still runs when the adoption reports no workspace id, rather than guessing one", async () => {
+ // Nothing to attribute the output to, so the run goes untracked rather than to the original.
+ consumeFiles.mockResolvedValue([]);
+ rechainPolicyOnDocument.mockResolvedValue({ ok: true, tracked: false });
+
+ await registry().DECRYPT?.run(policyContext(), "hunter2");
+
+ expect(rechainPolicyOnDocument).toHaveBeenCalledWith(
+ { policyId: "pol-1", fileId: "f-1" },
+ expect.any(File),
+ null,
+ );
+ });
+
+ it("leaves the row open when the re-run cannot deliver, and says why", async () => {
+ // Untracked, so the processed document never arrives: the unlocked input is not the point.
+ rechainPolicyOnDocument.mockResolvedValue({ ok: true, tracked: false });
+
+ expect(await registry().DECRYPT?.run(policyContext(), "hunter2")).toEqual({
+ ok: false,
+ message:
+ "The document was unlocked and the policy re-run started, but its result cannot be delivered here, so this failure stays open.",
+ });
+ // Adopted regardless: the password bought them the unlocked document either way.
+ expect(consumeFiles).toHaveBeenCalled();
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
+ it("shows a wrong password for what it is, and touches nothing else", async () => {
+ unlockLocalDocument.mockResolvedValue({
+ ok: false,
+ message: "The password is incorrect.",
+ });
+
+ expect(await registry().DECRYPT?.run(policyContext(), "wrong")).toEqual({
+ ok: false,
+ message: "The password is incorrect.",
+ });
+ expect(addFiles).not.toHaveBeenCalled();
+ expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
+ // The row is still a failure, so nothing may report it fixed.
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
+ it("neither re-runs nor closes the incident when the document cannot be taken in", async () => {
+ consumeFiles.mockRejectedValue(new Error("quota"));
+
+ expect(await registry().DECRYPT?.run(policyContext(), "hunter2")).toEqual({
+ ok: false,
+ message:
+ "The document was unlocked but could not be opened here. Try the tool directly.",
+ });
+ expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
+ it("says the unlock worked but the re-run did not, and leaves the row open", async () => {
+ rechainPolicyOnDocument.mockResolvedValue({
+ ok: false,
+ reason: "rejected",
+ message: "Queue full.",
+ });
+
+ expect(await registry().DECRYPT?.run(policyContext(), "hunter2")).toEqual({
+ ok: false,
+ message:
+ "The document was unlocked and opened here, but the policy could not be run on it again.",
+ });
+ // Adopted anyway: the password bought them the unlocked document, and that is theirs to keep.
+ expect(consumeFiles).toHaveBeenCalled();
+ // But nothing is fixed server-side, so the incident stays open.
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
+ it("never hands the password to anything but the unlock", async () => {
+ await registry().DECRYPT?.run(policyContext(), "hunter2");
+
+ // Everything downstream of the unlock: no payload, stash or id carries the password.
+ const downstream = [
+ ...addFiles.mock.calls,
+ ...rechainPolicyOnDocument.mock.calls,
+ ...reportNotificationResolved.mock.calls,
+ ];
+ expect(JSON.stringify(downstream)).not.toContain("hunter2");
+ // Not in the file that goes back to the policy either: those are the server's unlocked bytes.
+ const [, document] = rechainPolicyOnDocument.mock.calls[0] as [
+ unknown,
+ File,
+ unknown,
+ ];
+ expect(await bytesOf(document)).not.toContain("hunter2");
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/notifications/resolutions/unlock.ts b/frontend/editor/src/proprietary/components/notifications/resolutions/unlock.ts
new file mode 100644
index 0000000000..c4f4bd466b
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/notifications/resolutions/unlock.ts
@@ -0,0 +1,53 @@
+import {
+ retryWithPassword,
+ unlockLocalDocument,
+} from "@app/services/notificationRetry";
+import type { FileId } from "@app/types/file";
+import {
+ asFiles,
+ type Resolution,
+} from "@app/components/notifications/resolutions/resolution";
+
+export const unlock: Resolution = {
+ actionId: "DECRYPT",
+ toolId: "removePassword",
+ needsPassword: true,
+ async produce(target, context, password) {
+ // The stash knows a tool's parameters; a locked policy input just needs unlocking. Either
+ // way the call IS the re-run, which is why this fix declares no toolRerun.
+ const outcome =
+ target.kind === "tool"
+ ? await retryWithPassword(
+ target.payload,
+ password ?? "",
+ context.notification.fileId,
+ )
+ : await unlockLocalDocument(target.policy.fileId, password ?? "");
+ if (!outcome.ok) return outcome;
+
+ // Only a policy names an original to version; a tool retry keeps adding its output.
+ const originalId =
+ target.kind === "policy" ? (target.policy.fileId as FileId) : null;
+ return {
+ ok: true,
+ produced: asFiles(outcome.files ?? [])
+ .slice(0, 1)
+ .map((file) => ({ file, originalId })),
+ };
+ },
+ adoptFailed: (t) =>
+ t(
+ "notifications.adoptFailed",
+ "The document was unlocked but could not be opened here. Try the tool directly.",
+ ),
+ notRerun: (t) =>
+ t(
+ "notifications.unlockedNotRerun",
+ "The document was unlocked and opened here, but the policy could not be run on it again.",
+ ),
+ rerunUndelivered: (t) =>
+ t(
+ "notifications.unlockedRerunUndelivered",
+ "The document was unlocked and the policy re-run started, but its result cannot be delivered here, so this failure stays open.",
+ ),
+};
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx
index aac64bf79e..195d8a7b13 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx
@@ -88,7 +88,7 @@ describe("an upload waiting on its unlock prompt", () => {
it("runs once the prompt is answered, so skipping still records the failure", async () => {
// Skipping releases the file encrypted: the run fails, and that failure is the row the
- // bell offers Decrypt and retry on. Holding it back forever would lose that entirely.
+ // bell offers Unlock on. Holding it back forever would lose that entirely.
setPendingUnlocks(["file-locked"]);
setFileStubs([{ id: "file-locked", name: "locked.pdf" }]);
diff --git a/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.ts b/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.ts
index 0372072c41..15108c0807 100644
--- a/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.ts
+++ b/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.test.ts
@@ -29,7 +29,9 @@ vi.mock("@app/services/notificationRetry", async (importOriginal) => ({
}));
const rechainPolicyOnDocument = vi.fn();
+const canPlacePolicy = vi.fn();
vi.mock("@app/services/notificationPolicyRetry", () => ({
+ canPlacePolicy: (...args: unknown[]) => canPlacePolicy(...args),
rechainPolicyOnDocument: (...args: unknown[]) =>
rechainPolicyOnDocument(...args),
}));
@@ -132,9 +134,79 @@ beforeEach(() => {
rechainPolicyOnDocument
.mockReset()
.mockResolvedValue({ ok: true, tracked: true });
+ // Placeable by default: the browser still holds the policy the failure names.
+ canPlacePolicy.mockReset().mockReturnValue(true);
});
describe("useResolutionContinuation", () => {
+ it("carries a manual repair through a damaged document's policy and closes the row", async () => {
+ // Manual repair counts as the resolution, same as the button.
+ fetchNotifications.mockResolvedValue({
+ notifications: [
+ policyRow({
+ kindId: "INPUT_CORRUPTED",
+ fileId: "f-damaged",
+ actions: [
+ offer("REPAIR", "RESOLUTION"),
+ offer("OPEN_IN_TOOL", "OVERFLOW"),
+ ],
+ }),
+ ],
+ viewerReviewsTeam: false,
+ });
+
+ continuation()(
+ unlockRun({
+ operation: "repair",
+ inputFileIds: ["f-damaged"],
+ outputs: [
+ {
+ file: new File(["pdf"], "repaired.pdf", {
+ type: "application/pdf",
+ }),
+ fileId: "f-repaired",
+ sourceFileId: "f-damaged",
+ },
+ ],
+ }),
+ );
+
+ await waitFor(() =>
+ expect(reportNotificationResolved).toHaveBeenCalledWith("failure:evt-1"),
+ );
+ expect(rechainPolicyOnDocument).toHaveBeenCalledWith(
+ { policyId: "pol-1", fileId: "f-damaged" },
+ expect.any(File),
+ "f-repaired",
+ );
+ });
+
+ it("does not let a manual repair close a password failure on the same document", async () => {
+ // Both kinds can sit on one file, and repair is no answer to a missing password.
+ fetchNotifications.mockResolvedValue({
+ notifications: [policyRow({ fileId: "f-damaged" })],
+ viewerReviewsTeam: false,
+ });
+
+ continuation()(
+ unlockRun({
+ operation: "repair",
+ inputFileIds: ["f-damaged"],
+ outputs: [
+ {
+ file: new File(["pdf"], "repaired.pdf"),
+ fileId: "f-repaired",
+ sourceFileId: "f-damaged",
+ },
+ ],
+ }),
+ );
+
+ await waitFor(() => expect(fetchNotifications).toHaveBeenCalled());
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
+ });
+
it("carries a manual unlock through the failed policy and closes the row", async () => {
fetchNotifications.mockResolvedValue({
notifications: [policyRow()],
@@ -181,6 +253,22 @@ describe("useResolutionContinuation", () => {
expect(refreshNotificationsNow).not.toHaveBeenCalled();
});
+ it("submits nothing when the policy cannot be placed, however the fix arrived", async () => {
+ // The buttons are gated on this, and a manual run reaches the same submission, so without
+ // the same guard here the billed-but-uncollectable run is simply one route further along.
+ fetchNotifications.mockResolvedValue({
+ notifications: [policyRow()],
+ viewerReviewsTeam: false,
+ });
+ canPlacePolicy.mockReturnValue(false);
+
+ continuation()(unlockRun());
+
+ await waitFor(() => expect(fetchNotifications).toHaveBeenCalled());
+ expect(rechainPolicyOnDocument).not.toHaveBeenCalled();
+ expect(reportNotificationResolved).not.toHaveBeenCalled();
+ });
+
it("leaves the row open when the server refuses the re-run", async () => {
fetchNotifications.mockResolvedValue({
notifications: [policyRow()],
diff --git a/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.ts b/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.ts
index 6508c5a1dd..6831f24232 100644
--- a/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.ts
+++ b/frontend/editor/src/proprietary/hooks/tools/shared/useResolutionContinuation.ts
@@ -10,7 +10,14 @@ import {
loadRetryPayload,
stashMatchesKind,
} from "@app/services/notificationRetry";
-import { rechainPolicyOnDocument } from "@app/services/notificationPolicyRetry";
+import {
+ canPlacePolicy,
+ rechainPolicyOnDocument,
+} from "@app/services/notificationPolicyRetry";
+import {
+ isResolvingTool,
+ resolvingToolFor,
+} from "@app/components/notifications/resolutions";
import type {
SucceededToolRun,
ToolRunOutput,
@@ -18,13 +25,6 @@ import type {
export type { SucceededToolRun, ToolRunOutput };
-// "Decrypt and retry" is just the remove-password tool, so reaching it directly asks the same.
-
-/** Which tool's success counts as a kind's resolution. The server still decides WHO may fix it. */
-const RESOLUTION_TOOLS: Record<string, string> = {
- INPUT_PASSWORD_PROTECTED: "removePassword",
-};
-
export function useResolutionContinuation(): (run: SucceededToolRun) => void {
return useCallback((run: SucceededToolRun) => {
void continueResolutions(run);
@@ -57,7 +57,7 @@ async function continueResolutions(run: SucceededToolRun): Promise<void> {
/** Answered from local state alone, so an ordinary successful run costs no round-trip. */
async function couldResolveAnything(run: SucceededToolRun): Promise<boolean> {
- if (Object.values(RESOLUTION_TOOLS).includes(run.operation)) return true;
+ if (isResolvingTool(run.operation)) return true;
for (const fileId of run.inputFileIds) {
const stash = await loadRetryPayload(fileId);
if (stash?.operation === run.operation) return true;
@@ -73,11 +73,16 @@ async function continueRow(
// Same precedence as the bell's retry target: the policy shape is the more specific claim.
const attended = (row.sourceId ?? null) === null;
if (attended && row.policyId && row.fileId) {
- if (RESOLUTION_TOOLS[row.kindId] !== run.operation) return false;
- // The fix is still this reader's to make; it has simply arrived by other means.
- if (!row.actions.some((a) => a.enabled && a.slot === "RESOLUTION")) {
+ // As the bell does: a policy this browser cannot place would be submitted, billed, and
+ // collected by nobody. Arriving by a manual run rather than a button does not change that.
+ if (!canPlacePolicy(row.policyId)) return false;
+ // The server names the fix; the client only knows which tool performs it.
+ const resolution = row.actions.find((a) => a.slot === "RESOLUTION");
+ if (!resolution || resolvingToolFor(resolution.id) !== run.operation) {
return false;
}
+ // The fix is still this reader's to make; it has simply arrived by other means.
+ if (!resolution.enabled) return false;
const output = outputFor(row.fileId, run);
if (!output) return false;
diff --git a/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.ts b/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.ts
index ff37e60fe2..f9d65bcc47 100644
--- a/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.ts
+++ b/frontend/editor/src/proprietary/services/notificationPolicyRetry.test.ts
@@ -34,12 +34,15 @@ const policies = vi.hoisted(() => ({
}));
vi.mock("@app/services/policyStorage", () => ({
loadPolicies: () => policies.value,
+ // Derived from the same fixture, so swapping it invalidates the placeability cache exactly as
+ // a real write to storage would.
+ rawStoredPolicies: () => JSON.stringify(policies.value ?? null),
}));
// The REAL run store: a mock would assert the call and prove nothing about the record.
const { getRun, isDispatched, recordRunStart, resetPolicyRuns, updateRun } =
await import("@app/components/policies/policyRunStore");
-const { rerunPolicy, rechainPolicyOnDocument } =
+const { canPlacePolicy, rerunPolicy, rechainPolicyOnDocument } =
await import("@app/services/notificationPolicyRetry");
const target = { policyId: "pol-1", fileId: "f-1" };
@@ -52,6 +55,21 @@ beforeEach(() => {
resetPolicyRuns();
});
+describe("canPlacePolicy", () => {
+ it("is true only while this browser still holds the policy the failure names", () => {
+ expect(canPlacePolicy("pol-1")).toBe(true);
+
+ // What a team switch leaves behind: the row still names a policy this cache never had.
+ policies.value = { security: { backendId: "pol-other" } };
+ expect(canPlacePolicy("pol-1")).toBe(false);
+ });
+
+ it("is false rather than throwing when the cache cannot be read at all", () => {
+ policies.value = null as unknown as typeof policies.value;
+ expect(canPlacePolicy("pol-1")).toBe(false);
+ });
+});
+
describe("rerunPolicy", () => {
it("submits the stored document under the reference the failure named", async () => {
const document = new File(["%PDF-1.7"], "invoice.pdf", {
diff --git a/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts b/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts
index bb6b31beed..cd4733154e 100644
--- a/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts
+++ b/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts
@@ -4,7 +4,7 @@ import {
} from "@app/components/policies/policyRunStore";
import { orderedRewritingPolicies } from "@app/data/classificationPolicy";
import { fileStorage } from "@app/services/fileStorage";
-import { loadPolicies } from "@app/services/policyStorage";
+import { loadPolicies, rawStoredPolicies } from "@app/services/policyStorage";
import {
resolvePolicyRunTarget,
runStoredPolicy,
@@ -30,6 +30,46 @@ export type PolicyRerunOutcome =
/** The server refused the run. `message` is its own, or null when it gave nothing usable. */
| { ok: false; reason: "rejected"; message: string | null };
+/**
+ * Whether this browser still holds the policy the failure names. A run has to be filed against a
+ * local policy for {@code usePolicyAutoRun} to poll it and collect what it makes, so a run
+ * submitted without one is billed, produces output nobody here receives, and leaves the row open
+ * to be pressed and billed again. Callers gate the offer on this rather than discovering it after
+ * the run has gone.
+ *
+ * <p>False after a team switch, or against a cache written before the policy was renamed.
+ */
+export function canPlacePolicy(policyId: string): boolean {
+ return placeableBackendIds().has(policyId);
+}
+
+/**
+ * The placeable ids, rebuilt only when the stored policies actually change. Every notification
+ * row asks this while rendering, and the underlying read parses storage and reconciles it
+ * against the catalogue, which is far too much to repeat per row per render.
+ */
+let placeableCache: { raw: string | null; ids: Set<string> } | null = null;
+
+function placeableBackendIds(): Set<string> {
+ const raw = rawStoredPolicies();
+ if (placeableCache && placeableCache.raw === raw) {
+ return placeableCache.ids;
+ }
+
+ let ids = new Set<string>();
+ try {
+ ids = new Set(
+ Object.values(loadPolicies())
+ .map((state) => state.backendId)
+ .filter((backendId): backendId is string => backendId !== undefined),
+ );
+ } catch {
+ // Unreadable storage places nothing, which withholds the offer rather than misplacing it.
+ }
+ placeableCache = { raw, ids };
+ return ids;
+}
+
/** Re-run on the document still in this browser's storage, under the reference the failure named. */
export async function rerunPolicy(
target: PolicyRetryTarget,
diff --git a/frontend/editor/src/proprietary/services/policyStorage.ts b/frontend/editor/src/proprietary/services/policyStorage.ts
index 01cd7ebe84..29d0d53320 100644
--- a/frontend/editor/src/proprietary/services/policyStorage.ts
+++ b/frontend/editor/src/proprietary/services/policyStorage.ts
@@ -10,6 +10,21 @@ import { defaultRunOn } from "@app/policies/runOn";
import type { PoliciesByKey, PolicyState } from "@app/types/policies";
const STORAGE_KEY = "stirling-policies-state";
+
+/**
+ * The stored policies as written, before parsing or reconciling against the catalogue. A cheap
+ * identity for callers that cache a derivation of {@link loadPolicies} and need to know whether
+ * it is still current.
+ */
+export function rawStoredPolicies(): string | null {
+ try {
+ return typeof localStorage !== "undefined"
+ ? localStorage.getItem(STORAGE_KEY)
+ : null;
+ } catch {
+ return null;
+ }
+}
export const POLICIES_CHANGE_EVENT = "stirling:policies-changed";
function defaultState(policyKey: string): PolicyState {
diff --git a/testing/failure-kind-codes.json b/testing/failure-kind-codes.json
new file mode 100644
index 0000000000..dfd8e41f78
--- /dev/null
+++ b/testing/failure-kind-codes.json
@@ -0,0 +1,14 @@
+{
+ "$comment": [
+ "The ErrorCodes each FailureKind claims. Read by Java (FailureKindTest) and the frontend",
+ "(notificationRetry.test.ts) against their own copies, which must agree.",
+ "The bell matches a file's one stashed failure to a row by these codes, so a list that drifts",
+ "offers the wrong retry: a repair for a password prompt, or no offer at all.",
+ "Kinds claiming no codes are omitted; they are reached only through the classifier's fallback."
+ ],
+ "kinds": {
+ "INPUT_PASSWORD_PROTECTED": ["E004"],
+ "INPUT_CORRUPTED": ["E001", "E002", "E003"],
+ "COMPLIANCE_NOT_MET": ["E074"]
+ }
+}