Skip to content

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

Add logic for blocking files if their policy fails (#7997)

James Bruntoneac04b186eda
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index adf1e106dd..166cb20566 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7195,7 +7195,7 @@ applying = "Applying {{names}}"
applyingProgress = "Applying {{names}} ({{done}} of {{total}})"
exportFailureBody = "Security policies couldn't be applied. Files were exported as-is."
exportFailureTitle = "Exported without enforcement"
-failureBody = "{{failures}} of {{total}} file(s) couldn't be processed and were exported as-is."
+failureBody = "Some policies couldn't be applied to {{failures}} of {{total}} file(s)."
failureTitle = "Exported without full enforcement"
printPolicyAppliedBody = "This PDF was updated to meet a policy. Review the changes, then print again."
printPolicyAppliedTitle = "Policy applied before printing"
@@ -7228,6 +7228,24 @@ badgeRunning = "{{name}} running..."
blockingAction = "{{action}} blocked while enforcing policy, please wait..."
dismiss = "Dismiss overlay"
enforcingTitle = "Enforcing policy..."
+exportBlocked = "A required policy failed. The export was cancelled. Try exporting again."
+recoveryBody = "We couldn't apply a required policy to these files. Try again, or close the affected files to continue working."
+recoveryClose_one = "Close file"
+recoveryClose_other = "Close {{count}} files"
+recoveryClosing_one = "Closing file..."
+recoveryClosing_other = "Closing {{count}} files..."
+recoveryContactAdmin = "Contact your administrator for help."
+recoveryContactOwner = "Contact {{owner}} for help."
+recoveryError = "The action couldn't be completed. Try again."
+recoveryOwnedPolicy = "Check the policy settings, then retry."
+recoveryRetry_one = "Retry file"
+recoveryRetry_other = "Retry {{count}} files"
+recoveryRetrying_one = "Retrying file..."
+recoveryRetrying_other = "Retrying {{count}} files..."
+recoverySummary_one = "{{count}} file affected."
+recoverySummary_other = "{{count}} files affected."
+recoveryTechnicalDetails = "Technical details"
+recoveryTitle = "Policy enforcement failed"
viewAnyway = "View file (policy still enforcing)"
[policyOption]
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
index 35167564f7..7b81278a53 100644
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
+++ b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
@@ -6,6 +6,10 @@ import { pdfExportService } from "@app/services/pdfExportService";
import { exportProcessedDocumentsToFiles } from "@app/services/pdfExportHelpers";
import { FileId } from "@app/types/file";
import { PDFDocument, PDFPage } from "@app/types/pageEditor";
+import {
+ assertFilesNotBlocked,
+ policySourceIds,
+} from "@app/services/policyFileGuard";
type FileActions = ReturnType<typeof useFileActions>["actions"];
type FileSelectors = ReturnType<typeof useFileState>["selectors"];
@@ -69,6 +73,18 @@ export const usePageEditorExport = ({
clearPersistedDocument,
updateCurrentPages,
}: UsePageEditorExportParams) => {
+ const getPolicyIds = useCallback(() => {
+ const ids = new Set([
+ ...selectedFileIds,
+ ...(displayDocument?.pages.flatMap((page) =>
+ page.originalFileId ? [page.originalFileId] : [],
+ ) ?? []),
+ ]);
+ return [...ids].flatMap((id) => {
+ const stub = selectors.getStirlingFileStub(id);
+ return stub ? policySourceIds(stub) : [id];
+ });
+ }, [selectedFileIds, displayDocument, selectors]);
const getSourceFiles = useCallback((): Map<FileId, File> | null => {
const sourceFiles = new Map<FileId, File>();
@@ -107,7 +123,9 @@ export const usePageEditorExport = ({
if (!displayDocument || selectedPageIds.length === 0) return;
setExportLoading(true);
+ const policyIds = getPolicyIds();
try {
+ assertFilesNotBlocked(policyIds);
const processedDocuments =
documentManipulationService.applyDOMChangesToDocument(
displayDocument,
@@ -154,6 +172,7 @@ export const usePageEditorExport = ({
},
);
+ assertFilesNotBlocked(policyIds);
pdfExportService.downloadFile(result.blob, result.filename);
setHasUnsavedChanges(false);
setSplitPositions(new Set());
@@ -168,6 +187,8 @@ export const usePageEditorExport = ({
splitPositions,
getSourceFiles,
getExportFilename,
+ selectedFileIds,
+ getPolicyIds,
setHasUnsavedChanges,
setExportLoading,
]);
@@ -176,7 +197,9 @@ export const usePageEditorExport = ({
if (!displayDocument) return;
setExportLoading(true);
+ const policyIds = getPolicyIds();
try {
+ assertFilesNotBlocked(policyIds);
const processedDocuments =
documentManipulationService.applyDOMChangesToDocument(
displayDocument,
@@ -219,9 +242,11 @@ export const usePageEditorExport = ({
const zipBlob = await zip.generateAsync({ type: "blob" });
const zipFilename = exportFilename.replace(/\.pdf$/i, ".zip");
+ assertFilesNotBlocked(policyIds);
pdfExportService.downloadFile(zipBlob, zipFilename);
} else {
const file = files[0];
+ assertFilesNotBlocked(policyIds);
pdfExportService.downloadFile(file, file.name);
}
@@ -237,6 +262,8 @@ export const usePageEditorExport = ({
splitPositions,
getSourceFiles,
getExportFilename,
+ selectedFileIds,
+ getPolicyIds,
setHasUnsavedChanges,
setExportLoading,
]);
@@ -245,7 +272,9 @@ export const usePageEditorExport = ({
if (!displayDocument) return;
setExportLoading(true);
+ const policyIds = getPolicyIds();
try {
+ assertFilesNotBlocked(policyIds);
const processedDocuments =
documentManipulationService.applyDOMChangesToDocument(
displayDocument,
@@ -277,6 +306,8 @@ export const usePageEditorExport = ({
exportFilename,
);
+ assertFilesNotBlocked(policyIds);
+
// Add "_multitool" suffix to filenames
const renamedFiles = files.map((file) => {
const nameParts = file.name.match(/^(.+?)(\.pdf)$/i);
@@ -304,6 +335,7 @@ export const usePageEditorExport = ({
await actions.removeFiles(sourceFileIds, true);
}
+ assertFilesNotBlocked(policyIds);
const newStirlingFiles = await actions.addFiles(renamedFiles, {
selectFiles: true,
skipUploadTracking: true,
@@ -339,8 +371,9 @@ export const usePageEditorExport = ({
splitPositions,
getSourceFiles,
getExportFilename,
- actions,
selectedFileIds,
+ getPolicyIds,
+ actions,
setHasUnsavedChanges,
setExportLoading,
clearPersistedDocument,
diff --git a/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx b/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
index fa23005c23..744698e612 100644
--- a/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
+++ b/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
@@ -24,6 +24,11 @@ import {
} from "@app/services/shareBundleUtils";
import { truncateCenter } from "@app/utils/textUtils";
import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
+import {
+ assertFilesNotBlocked,
+ policySourceIds,
+} from "@app/services/policyFileGuard";
+import { alert } from "@app/components/toast";
import styles from "@app/components/shared/FileSelectorPicker.module.css";
import "@app/components/shared/FileSidebarFileItem.css";
@@ -243,6 +248,16 @@ export function FileSelectorPicker({
const loadAndSelect = useCallback(
async (stub: StirlingFileStub) => {
if (loadingId) return;
+ try {
+ assertFilesNotBlocked(policySourceIds(stub));
+ } catch {
+ alert({
+ alertType: "warning",
+ title: t("policy.recoveryTitle"),
+ body: t("policy.recoveryBody"),
+ });
+ return;
+ }
// Workbench file — get StirlingFile directly from FileContext (no loading needed)
if (workbenchIdSet.has(stub.id)) {
@@ -322,6 +337,7 @@ export function FileSelectorPicker({
// Non-fatal — thumbnail simply won't show
}
}
+ assertFilesNotBlocked(policySourceIds(resolvedStub));
onSelect({ stub: resolvedStub, stirlingFile });
setIsOpen(false);
}
@@ -331,7 +347,7 @@ export function FileSelectorPicker({
setLoadingId(null);
}
},
- [loadingId, workbenchIdSet, selectors, onSelect],
+ [loadingId, workbenchIdSet, selectors, onSelect, t],
);
const handleUpload = useCallback(
diff --git a/frontend/editor/src/core/components/tools/RightSidebar.tsx b/frontend/editor/src/core/components/tools/RightSidebar.tsx
index a4bc4f109d..7db8be8258 100644
--- a/frontend/editor/src/core/components/tools/RightSidebar.tsx
+++ b/frontend/editor/src/core/components/tools/RightSidebar.tsx
@@ -4,8 +4,6 @@ import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useSidebarContext } from "@app/contexts/SidebarContext";
import { useIsMobile } from "@app/hooks/useIsMobile";
import ToolPanel from "@app/components/tools/ToolPanel";
-import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
-import { PolicyAutoRunController } from "@app/components/policies/PolicyAutoRunController";
import { useFavoriteToolItems } from "@app/hooks/tools/useFavoriteToolItems";
import { useToolSections } from "@app/hooks/useToolSections";
import type { SubcategoryGroup } from "@app/hooks/useToolSections";
@@ -55,7 +53,6 @@ export default function RightSidebar() {
favoriteTools,
} = useToolWorkflow();
- const policiesEnabled = usePoliciesEnabled();
const fullscreenExpanded = useIsFullscreenExpanded();
const fullscreenGeometry = useToolPanelGeometry({
enabled: fullscreenExpanded,
@@ -156,8 +153,6 @@ export default function RightSidebar() {
padding: "0",
}}
>
- {/* Headless: enforces enabled policies on every uploaded file. */}
- {policiesEnabled && <PolicyAutoRunController />}
{!fullscreenExpanded && !isPanelVisible && !isMobile && (
<div className="tool-panel__collapsed-strip">
<div className="tool-panel__collapsed-top">
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
index 13fc7dcecc..c1fad547bb 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
@@ -1,5 +1,9 @@
import { useCallback, useRef, useEffect, useContext } from "react";
import apiClient from "@app/services/apiClient";
+import {
+ assertFilesNotBlocked,
+ policySourceIds,
+} from "@app/services/policyFileGuard";
import { useTranslation } from "react-i18next";
import { useFileContext } from "@app/contexts/FileContext";
import { useNavigationActions } from "@app/contexts/NavigationContext";
@@ -224,6 +228,16 @@ export const useToolOperation = <TParams>(
const executeOperation = useCallback(
async (params: TParams, selectedFiles: StirlingFile[]): Promise<void> => {
+ const policyIds = selectedFiles.flatMap((file) => {
+ const stub = selectors.getStirlingFileStub(file.fileId);
+ return stub ? policySourceIds(stub) : [file.fileId];
+ });
+ try {
+ assertFilesNotBlocked(policyIds);
+ } catch (error) {
+ actions.setError(extractErrorMessage(error));
+ return;
+ }
// Validation
if (selectedFiles.length === 0) {
actions.setError(t("noFileSelected", "No file loaded"));
@@ -302,6 +316,7 @@ export const useToolOperation = <TParams>(
window.addEventListener(FILE_EVENTS.markError, errorListener);
try {
+ assertFilesNotBlocked(policyIds);
let processedFiles: File[];
let successSourceIds: FileId[] = [];
@@ -480,6 +495,7 @@ export const useToolOperation = <TParams>(
}
if (processedFiles.length > 0) {
+ assertFilesNotBlocked(policyIds);
trackEditorOperation(
config.operationType,
successSourceIds.length || validFiles.length,
@@ -496,6 +512,7 @@ export const useToolOperation = <TParams>(
actions.setGeneratingThumbnails(false);
actions.setThumbnails(thumbnails);
+ assertFilesNotBlocked(policyIds);
// Determine whether outputs are new versions of their inputs or independent artifacts.
// A version operation produces exactly one output per successful input, all in the same
@@ -576,6 +593,7 @@ export const useToolOperation = <TParams>(
inputCount: inputFileIds.length,
toConsume: toConsumeInputIds.length,
});
+ assertFilesNotBlocked(policyIds);
const outputFileIds = await consumeFiles(
toConsumeInputIds,
outputStirlingFiles,
@@ -650,6 +668,7 @@ export const useToolOperation = <TParams>(
inputCount: inputFileIds.length,
toConsume: toConsumeInputIds.length,
});
+ assertFilesNotBlocked(policyIds);
const outputFileIds = await consumeFiles(
toConsumeInputIds,
outputStirlingFiles,
diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsx
index 16a7c6934d..46b92e6298 100644
--- a/frontend/editor/src/core/pages/HomePage.tsx
+++ b/frontend/editor/src/core/pages/HomePage.tsx
@@ -38,6 +38,8 @@ import {
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
import { rememberSettingsOrigin } from "@app/utils/settingsNavigation";
import { HomePageExtensions } from "@app/components/home/HomePageExtensions";
+import { PolicyAutoRunController } from "@app/components/policies/PolicyAutoRunController";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";
import {
@@ -101,6 +103,7 @@ type MobileView = "tools" | "workbench";
export default function HomePage() {
const { t } = useTranslation();
+ const policiesEnabled = usePoliciesEnabled();
const { sidebarRefs } = useSidebarContext();
const { quickAccessRef } = sidebarRefs;
@@ -469,6 +472,7 @@ export default function HomePage() {
return (
<div className="h-screen overflow-hidden">
<HomePageExtensions />
+ {policiesEnabled && <PolicyAutoRunController />}
<QuickNavHostBridge
requestNavigation={requestNavigation}
readerMode={readerMode}
diff --git a/frontend/editor/src/core/services/downloadService.ts b/frontend/editor/src/core/services/downloadService.ts
index c61015f36d..fa2bfe158d 100644
--- a/frontend/editor/src/core/services/downloadService.ts
+++ b/frontend/editor/src/core/services/downloadService.ts
@@ -1,3 +1,4 @@
+import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
export interface DownloadRequest {
data: Blob | File;
filename: string;
@@ -15,6 +16,7 @@ export interface DownloadResult {
export async function downloadFile(
request: DownloadRequest,
): Promise<DownloadResult> {
+ assertFilesNotBlocked([request.fileId]);
const url = URL.createObjectURL(request.data);
const link = document.createElement("a");
@@ -34,6 +36,7 @@ export async function downloadFromUrl(
filename: string,
localPath?: string,
): Promise<DownloadResult> {
+ assertFilesNotBlocked();
const link = document.createElement("a");
link.href = url;
link.download = filename;
diff --git a/frontend/editor/src/core/services/exportWithPolicy.ts b/frontend/editor/src/core/services/exportWithPolicy.ts
index 207e37d78e..970535dbe1 100644
--- a/frontend/editor/src/core/services/exportWithPolicy.ts
+++ b/frontend/editor/src/core/services/exportWithPolicy.ts
@@ -2,8 +2,8 @@
* Export entry points call {@link downloadFileWithPolicy} instead of
* {@link downloadFile} so any "export"-triggered policy enforces on the file
* before it's downloaded. The enforcement itself is proprietary (a no-op in the
- * core build via the `@app/services/policyExport` stub), and never hard-blocks:
- * on failure the original file is downloaded.
+ * core build via the `@app/services/policyExport` stub). Required-policy failures
+ * cancel the export; ordinary pipeline failures may download the original.
*/
import {
diff --git a/frontend/editor/src/core/services/policyBlockRegistry.ts b/frontend/editor/src/core/services/policyBlockRegistry.ts
new file mode 100644
index 0000000000..cd7e87e3a3
--- /dev/null
+++ b/frontend/editor/src/core/services/policyBlockRegistry.ts
@@ -0,0 +1,29 @@
+import type { StirlingFileStub } from "@app/types/fileContext";
+
+/** Register documents retained outside the workspace until their owning tool releases them. */
+export function registerPolicyFileUsage(
+ _files: StirlingFileStub[],
+): () => void {
+ return () => {};
+}
+
+/** Whether a required policy currently prevents use of this document. */
+export function isFileBlocked(_fileId: string): boolean {
+ return false;
+}
+
+/** Whether the open editor is waiting for policy recovery. */
+export function isEditorPolicyBlocked(): boolean {
+ return false;
+}
+
+/** Includes consumed ancestors so an edit cannot bypass a failure on its input. */
+export function policySourceIds(
+ file: Pick<StirlingFileStub, "id" | "parentFileId" | "sourceFileIds">,
+): string[] {
+ return [
+ file.id,
+ ...(file.sourceFileIds ?? []),
+ ...(file.parentFileId ? [file.parentFileId] : []),
+ ];
+}
diff --git a/frontend/editor/src/core/services/policyFileGuard.ts b/frontend/editor/src/core/services/policyFileGuard.ts
new file mode 100644
index 0000000000..d4a1ba2c71
--- /dev/null
+++ b/frontend/editor/src/core/services/policyFileGuard.ts
@@ -0,0 +1,24 @@
+import i18n from "i18next";
+import {
+ isEditorPolicyBlocked,
+ isFileBlocked,
+} from "@app/services/policyBlockRegistry";
+export { policySourceIds } from "@app/services/policyBlockRegistry";
+
+/** A required policy prevents using or exporting the document. */
+export class PolicyBlockedError extends Error {
+ constructor() {
+ super(i18n.t("policy.recoveryBody"));
+ this.name = "PolicyBlockedError";
+ }
+}
+
+/** Recheck after asynchronous preparation, immediately before using the resulting bytes. */
+export function assertFilesNotBlocked(
+ fileIds: Iterable<string | undefined> = [],
+): void {
+ if (isEditorPolicyBlocked()) throw new PolicyBlockedError();
+ for (const fileId of fileIds) {
+ if (fileId && isFileBlocked(fileId)) throw new PolicyBlockedError();
+ }
+}
diff --git a/frontend/editor/src/core/services/serverStorageUpload.ts b/frontend/editor/src/core/services/serverStorageUpload.ts
index 39780055f8..3c88bc0582 100644
--- a/frontend/editor/src/core/services/serverStorageUpload.ts
+++ b/frontend/editor/src/core/services/serverStorageUpload.ts
@@ -1,4 +1,8 @@
import apiClient from "@app/services/apiClient";
+import {
+ assertFilesNotBlocked,
+ policySourceIds,
+} from "@app/services/policyFileGuard";
import { fileStorage } from "@app/services/fileStorage";
import {
buildHistoryBundle,
@@ -22,6 +26,7 @@ export async function uploadHistoryChain(
originalFileId: FileId,
existingRemoteId?: number,
): Promise<{ remoteId: number; updatedAt: number; chain: StirlingFileStub[] }> {
+ assertFilesNotBlocked([originalFileId]);
const chain = await fileStorage.getHistoryChainStubs(originalFileId);
if (chain.length === 0) {
throw new Error("No history chain found.");
@@ -50,6 +55,7 @@ export async function uploadHistoryChain(
formData.append("file", finalFile, finalFile.name);
formData.append("historyBundle", bundleFile, bundleFile.name);
formData.append("auditLog", auditLog, auditLog.name);
+ assertFilesNotBlocked(chain.flatMap(policySourceIds));
if (existingRemoteId) {
const response = await apiClient.put(
@@ -74,6 +80,7 @@ export async function uploadHistoryChains(
originalFileIds: FileId[],
existingRemoteId?: number,
): Promise<{ remoteId: number; updatedAt: number; chain: StirlingFileStub[] }> {
+ assertFilesNotBlocked(originalFileIds);
const uniqueRoots = Array.from(new Set(originalFileIds));
const chainMap = new Map<FileId, StirlingFileStub[]>();
const combinedChain: StirlingFileStub[] = [];
@@ -127,6 +134,7 @@ export async function uploadHistoryChains(
formData.append("file", shareFile, shareFile.name);
formData.append("historyBundle", bundleFile, bundleFile.name);
formData.append("auditLog", auditLog, auditLog.name);
+ assertFilesNotBlocked(combinedChain.flatMap(policySourceIds));
if (existingRemoteId) {
const response = await apiClient.put(
diff --git a/frontend/editor/src/core/tools/Compare.tsx b/frontend/editor/src/core/tools/Compare.tsx
index 6242e12dab..d87e0efa1c 100644
--- a/frontend/editor/src/core/tools/Compare.tsx
+++ b/frontend/editor/src/core/tools/Compare.tsx
@@ -26,6 +26,7 @@ import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbn
import type { CompareWorkbenchData } from "@app/types/compare";
import { getDefaultWorkbench } from "@app/types/workbench";
import { truncateCenter } from "@app/utils/textUtils";
+import { registerPolicyFileUsage } from "@app/services/policyBlockRegistry";
import {
FileSelectorPicker as PopoverFileSelector,
FileSelectorResult,
@@ -69,6 +70,13 @@ const Compare = (props: BaseToolProps) => {
// Slot state — files loaded directly for comparison, never added to workbench
const [baseSlot, setBaseSlot] = useState<FileSelectorResult | null>(null);
const [compSlot, setCompSlot] = useState<FileSelectorResult | null>(null);
+ useEffect(
+ () =>
+ registerPolicyFileUsage(
+ [baseSlot, compSlot].flatMap((slot) => (slot ? [slot.stub] : [])),
+ ),
+ [baseSlot, compSlot],
+ );
// Sync params fileIds from slots (needed for operation result matching)
useEffect(() => {
diff --git a/frontend/editor/src/core/tools/formFill/useFormCommit.ts b/frontend/editor/src/core/tools/formFill/useFormCommit.ts
index 6616d727d0..89c361dae6 100644
--- a/frontend/editor/src/core/tools/formFill/useFormCommit.ts
+++ b/frontend/editor/src/core/tools/formFill/useFormCommit.ts
@@ -6,6 +6,7 @@ import { useState, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { isAxiosError } from "axios";
import { dispatchFormApply } from "@app/tools/formFill/formFillEvents";
+import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
/**
* responseType "blob" means an error's ProblemDetail arrives as a Blob, so read
@@ -43,7 +44,9 @@ export function useFormCommit(onApplied?: (blob: Blob) => void) {
setCommitting(true);
setError(null);
try {
+ assertFilesNotBlocked();
const blob = await run();
+ assertFilesNotBlocked();
dispatchFormApply(blob);
onApplied?.(blob);
} catch (err) {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
index 3faeb40027..4aebf92fed 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
@@ -1,3 +1,7 @@
+import {
+ assertFilesNotBlocked,
+ policySourceIds,
+} from "@app/services/policyFileGuard";
import { useCallback, useEffect, useRef, useState } from "react";
import { Alert, Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
@@ -128,6 +132,10 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const parentStub = sourceId
? selectors.getStirlingFileStub(sourceId)
: null;
+ const policyIds = parentStub
+ ? policySourceIds(parentStub)
+ : [sourceId ?? undefined];
+ assertFilesNotBlocked(policyIds);
setApplying(true);
try {
if (sourceId && parentStub) {
@@ -136,6 +144,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
parentStub,
"pdfTextEditor",
);
+ assertFilesNotBlocked(policyIds);
await consumeFiles([sourceId], stirlingFiles, stubs);
// Claim the replacement before releasing the hold, otherwise the
// editor sees an unfamiliar selection and re-opens the file it just
@@ -162,7 +171,9 @@ export default function PdfTextEditor(_props: BaseToolProps) {
if (!store.document || savingRef.current) return;
savingRef.current = true;
store.setError(null);
+ const sourceId = sourceFileIdRef.current;
try {
+ assertFilesNotBlocked([sourceId ?? undefined]);
// Yield once so React can paint the disabled/saving state before the
// synchronous PDFium serialize blocks the main thread.
await new Promise((resolve) => setTimeout(resolve, 0));
@@ -175,9 +186,13 @@ export default function PdfTextEditor(_props: BaseToolProps) {
);
// Apply first and unconditionally. Gating the write-back on the browser
// download dialog meant cancelling it silently discarded the save.
+ assertFilesNotBlocked([sourceId ?? undefined]);
await applyToWorkbench(blob, filename);
store.markSaved(exported);
- if (download) await downloadFile({ data: blob, filename });
+ if (download) {
+ assertFilesNotBlocked([sourceId ?? undefined]);
+ await downloadFile({ data: blob, filename });
+ }
} catch (err) {
// Surface the failure instead of silently dropping it - the user
// must not believe a broken save succeeded.
diff --git a/frontend/editor/src/desktop/services/downloadService.ts b/frontend/editor/src/desktop/services/downloadService.ts
index b2642370bc..e61cd8f2ee 100644
--- a/frontend/editor/src/desktop/services/downloadService.ts
+++ b/frontend/editor/src/desktop/services/downloadService.ts
@@ -2,6 +2,7 @@ import type {
DownloadRequest,
DownloadResult,
} from "@core/services/downloadService";
+import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
import {
saveToLocalPath,
showSaveDialog,
@@ -12,6 +13,7 @@ export type { DownloadRequest, DownloadResult };
export async function downloadFile(
request: DownloadRequest,
): Promise<DownloadResult> {
+ assertFilesNotBlocked([request.fileId]);
if (request.localPath) {
const result = await saveToLocalPath(request.data, request.localPath);
if (!result.success) {
@@ -25,6 +27,7 @@ export async function downloadFile(
return { cancelled: true };
}
+ assertFilesNotBlocked([request.fileId]);
const result = await saveToLocalPath(request.data, savePath);
if (!result.success) {
throw new Error(result.error || "Failed to save file");
diff --git a/frontend/editor/src/desktop/services/localFileSaveService.ts b/frontend/editor/src/desktop/services/localFileSaveService.ts
index 6232c8a7c2..bd8e2bc009 100644
--- a/frontend/editor/src/desktop/services/localFileSaveService.ts
+++ b/frontend/editor/src/desktop/services/localFileSaveService.ts
@@ -3,6 +3,7 @@ import type {
MultiFileSaveResult,
} from "@core/services/localFileSaveService";
export type { SaveResult, MultiFileSaveResult };
+import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
/**
* Save file data to a local filesystem path (Tauri desktop only)
@@ -18,6 +19,7 @@ export async function saveToLocalPath(
try {
const { writeFile } = await import("@tauri-apps/plugin-fs");
const arrayBuffer = await data.arrayBuffer();
+ assertFilesNotBlocked();
await writeFile(filePath, new Uint8Array(arrayBuffer));
return { success: true };
} catch (error) {
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyAutoRunController.tsx b/frontend/editor/src/proprietary/components/policies/PolicyAutoRunController.tsx
index ead0cb1038..4d64c68fac 100644
--- a/frontend/editor/src/proprietary/components/policies/PolicyAutoRunController.tsx
+++ b/frontend/editor/src/proprietary/components/policies/PolicyAutoRunController.tsx
@@ -1,15 +1,14 @@
import { usePolicyAutoRun } from "@app/components/policies/usePolicyAutoRun";
import { usePolicyLocalPasses } from "@app/components/policies/usePolicyLocalPasses";
+import { PolicyRecoveryGate } from "@app/components/policies/PolicyRecoveryGate";
/**
- * Headless controller that drives policy auto-run (enforce every enabled policy
- * on every uploaded file). Mounted once wherever the editor is open so runs fire
- * regardless of whether the policy panel is visible. Renders nothing.
+ * Runs policies and recovery once per editor, independent of the active tool or sidebar.
*/
export function PolicyAutoRunController() {
// Server-dispatched, file-producing policies and their chain.
usePolicyAutoRun();
// Policies with a browser-side fast path (e.g. classification's heuristic), run generically.
usePolicyLocalPasses();
- return null;
+ return <PolicyRecoveryGate />;
}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.css b/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.css
new file mode 100644
index 0000000000..b827b36e9d
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.css
@@ -0,0 +1,77 @@
+.policy-recovery {
+ margin: auto;
+ padding: 1.5rem;
+ width: min(36rem, calc(100vw - 2rem));
+ max-height: calc(100dvh - 2rem);
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ border: 1px solid var(--c-border);
+ border-radius: var(--radius-xl);
+ background: var(--c-surface);
+ color: var(--c-text);
+ font-family: var(--font-sans);
+}
+
+.policy-recovery::backdrop {
+ background: var(--c-overlay);
+}
+
+.policy-recovery h2 {
+ margin: 0 0 0.5rem;
+ font-size: 1.25rem;
+}
+
+.policy-recovery p {
+ margin: 0.5rem 0;
+}
+
+.policy-recovery__hint {
+ font-size: 0.875rem;
+ color: var(--c-text-muted);
+}
+
+.policy-recovery__policies {
+ margin-top: 1rem;
+ padding-top: 1rem;
+ border-top: 1px solid var(--c-border);
+}
+
+.policy-recovery__policy + .policy-recovery__policy {
+ margin-top: 0.75rem;
+}
+
+.policy-recovery__policy,
+.policy-recovery__error {
+ overflow-wrap: anywhere;
+}
+
+.policy-recovery__details {
+ margin-top: 1rem;
+ color: var(--c-text-muted);
+ font-size: 0.875rem;
+}
+
+.policy-recovery__details summary {
+ cursor: pointer;
+}
+
+.policy-recovery__errors {
+ max-height: 12rem;
+ overflow: auto;
+}
+
+.policy-recovery__error {
+ margin-top: 0.75rem;
+}
+
+.policy-recovery__details pre {
+ white-space: pre-wrap;
+ font-size: inherit;
+}
+
+.policy-recovery__actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ margin-top: 1rem;
+}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.test.tsx b/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.test.tsx
new file mode 100644
index 0000000000..7ec3cb82c0
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.test.tsx
@@ -0,0 +1,511 @@
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createInstance } from "i18next";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { parse } from "smol-toml";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import { createNewStirlingFileStub } from "@app/types/fileContext";
+import type { PolicyRunRecord } from "@app/components/policies/policyRunStore";
+
+const translations = parse(
+ readFileSync(
+ join(__dirname, "../../../../public/locales/en-US/translation.toml"),
+ "utf8",
+ ),
+);
+const testI18n = createInstance();
+await testI18n.init({
+ lng: "en-US",
+ resources: { "en-US": { translation: translations } },
+});
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: testI18n.t.bind(testI18n), i18n: testI18n }),
+ initReactI18next: { type: "3rdParty", init: vi.fn() },
+}));
+
+const harness = vi.hoisted(() => ({
+ files: [] as StirlingFileStub[],
+ user: { username: "alice", email: "[email protected]" },
+ removeFiles: vi.fn(),
+ pauseHotkeys: vi.fn(),
+ resumeHotkeys: vi.fn(),
+ navigation: { setSelectedTool: vi.fn(), setWorkbench: vi.fn() },
+ setPreviewFile: vi.fn(),
+ selectors: { getStirlingFileStubs: (): StirlingFileStub[] => harness.files },
+}));
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({ user: harness.user }),
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useAllFiles: () => ({ fileStubs: harness.files }),
+ useFileSelectors: () => harness.selectors,
+ useFileManagement: () => ({ removeFiles: harness.removeFiles }),
+}));
+vi.mock("@app/contexts/HotkeyContext", () => ({
+ useHotkeys: () => ({
+ pauseHotkeys: harness.pauseHotkeys,
+ resumeHotkeys: harness.resumeHotkeys,
+ areHotkeysPaused: false,
+ }),
+}));
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigationActions: () => ({ actions: harness.navigation }),
+}));
+vi.mock("@app/contexts/ToolWorkflowContext", () => ({
+ useToolWorkflow: () => ({ setPreviewFile: harness.setPreviewFile }),
+}));
+vi.mock("@app/services/policyDispatch", () => ({ runPolicyOnFile: vi.fn() }));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { getStirlingFileStub: vi.fn() },
+}));
+vi.mock("@app/services/policyCatalog", () => ({
+ loadPolicyCatalog: () => ({
+ categories: [{ id: "security", label: "Security" }],
+ }),
+}));
+import { PolicyRecoveryGate } from "@app/components/policies/PolicyRecoveryGate";
+import {
+ recordRunStart,
+ resetPolicyRuns,
+ updateRun,
+} from "@app/components/policies/policyRunStore";
+import { updatePolicy } from "@app/services/policyStorage";
+import {
+ isFileBlocked,
+ isEditorPolicyBlocked,
+ registerPolicyFileUsage,
+} from "@app/services/policyBlockRegistry";
+import { runPolicyOnFile } from "@app/services/policyDispatch";
+import { fileStorage } from "@app/services/fileStorage";
+
+function failed(
+ file: StirlingFileStub,
+ over: Partial<PolicyRunRecord> = {},
+): PolicyRunRecord {
+ return {
+ runId: file.id,
+ policyKey: "security",
+ fileId: file.id,
+ fileName: file.name,
+ fileSize: 1,
+ target: "local",
+ status: "FAILED",
+ outputs: [],
+ error: "Policy service unavailable",
+ startedAt: 1,
+ ...over,
+ };
+}
+
+function app() {
+ return (
+ <MantineProvider>
+ <textarea aria-label="Unsaved work" defaultValue="Keep my edits" />
+ <PolicyRecoveryGate />
+ </MantineProvider>
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ resetPolicyRuns();
+ updatePolicy("security", { required: true, backendId: "backend-security" });
+ harness.files = [createNewStirlingFileStub(new File(["pdf"], "failed.pdf"))];
+ vi.mocked(fileStorage.getStirlingFileStub).mockImplementation(
+ async (id) => harness.files.find((file) => file.id === id) ?? null,
+ );
+ harness.removeFiles.mockResolvedValue(undefined);
+ vi.mocked(runPolicyOnFile).mockResolvedValue(undefined);
+ // Modal/inert behaviour is checked in Chromium; jsdom only models the open state.
+ Object.defineProperty(HTMLDialogElement.prototype, "showModal", {
+ configurable: true,
+ value: function (this: HTMLDialogElement) {
+ this.open = true;
+ },
+ });
+ Object.defineProperty(HTMLDialogElement.prototype, "close", {
+ configurable: true,
+ value: function (this: HTMLDialogElement) {
+ this.open = false;
+ },
+ });
+});
+afterEach(() => cleanup());
+
+describe("editor policy recovery", () => {
+ it("covers documents retained by a tool outside the workspace", () => {
+ const file = harness.files[0];
+ harness.files = [];
+ recordRunStart(failed(file));
+ render(app());
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ let release = () => {};
+ act(() => {
+ release = registerPolicyFileUsage([file]);
+ });
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(isEditorPolicyBlocked()).toBe(true);
+ act(() => release());
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+ it("pauses for a persisted required failure without unmounting the editor", () => {
+ const view = render(app());
+ const editor = screen.getByRole("textbox");
+ fireEvent.change(editor, { target: { value: "Unsaved changes" } });
+ act(() => recordRunStart(failed(harness.files[0])));
+ expect(
+ screen.getByRole("dialog", { name: "Policy enforcement failed" }),
+ ).toHaveAttribute("open");
+ expect(screen.getByText("1 file affected.")).toBeVisible();
+ expect(screen.getByText("failed.pdf")).not.toBeVisible();
+ expect(
+ screen.getByText("Technical details").closest("details"),
+ ).not.toHaveAttribute("open");
+ expect(editor).toHaveValue("Unsaved changes");
+ expect(harness.pauseHotkeys).toHaveBeenCalled();
+ view.unmount();
+ render(app());
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ });
+
+ it("directs users to the policy owner when it belongs to someone else", () => {
+ updatePolicy("security", { owner: "[email protected]" });
+ recordRunStart(failed(harness.files[0]));
+ render(app());
+ expect(
+ screen.getByText("Contact [email protected] for help."),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Check the policy settings, then retry."),
+ ).not.toBeInTheDocument();
+ });
+
+ it.each(["alice", "[email protected]"])(
+ "directs the owner to their policy settings when identified by %s",
+ (owner) => {
+ updatePolicy("security", { owner });
+ recordRunStart(failed(harness.files[0]));
+ render(app());
+ expect(
+ screen.getByText("Check the policy settings, then retry."),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Contact [email protected] for help."),
+ ).not.toBeInTheDocument();
+ },
+ );
+
+ it("directs users to their administrator when the owner is unavailable", () => {
+ recordRunStart(failed(harness.files[0]));
+ render(app());
+ expect(
+ screen.getByText("Contact your administrator for help."),
+ ).toBeInTheDocument();
+ });
+
+ it("isolates editor handlers without cancelling browser shortcuts or clipboard defaults", () => {
+ recordRunStart(failed(harness.files[0]));
+ const shortcut = vi.fn();
+ const clipboard = vi.fn();
+ window.addEventListener("keydown", shortcut);
+ document.addEventListener("paste", clipboard);
+ const view = render(app());
+ try {
+ const dialog = screen.getByRole("dialog");
+ fireEvent.keyDown(dialog, { key: "s", ctrlKey: true });
+ fireEvent.keyDown(dialog, { key: "z", metaKey: true });
+ fireEvent.keyDown(dialog, { key: "Delete" });
+ fireEvent.keyDown(dialog, { key: "Tab" });
+ for (const binding of [
+ { key: "r", ctrlKey: true },
+ { key: "r", metaKey: true },
+ { key: "r", metaKey: true, shiftKey: true },
+ { key: "F5" },
+ { key: "F12" },
+ { key: "i", ctrlKey: true, shiftKey: true },
+ { key: "i", metaKey: true, altKey: true },
+ { key: "l", metaKey: true },
+ { key: "l", ctrlKey: true },
+ { key: "c", metaKey: true },
+ { key: "c", ctrlKey: true },
+ ]) {
+ expect(fireEvent.keyDown(dialog, binding)).toBe(true);
+ expect(fireEvent.keyUp(dialog, binding)).toBe(true);
+ }
+ expect(fireEvent.copy(dialog)).toBe(true);
+ expect(fireEvent.cut(dialog)).toBe(true);
+ expect(fireEvent.paste(dialog)).toBe(true);
+ const cancel = new Event("cancel", { cancelable: true });
+ dialog.dispatchEvent(cancel);
+ expect(cancel.defaultPrevented).toBe(true);
+ expect(shortcut).not.toHaveBeenCalled();
+ expect(clipboard).not.toHaveBeenCalled();
+ view.unmount();
+ fireEvent.keyDown(window, { key: "s", ctrlKey: true });
+ expect(shortcut).toHaveBeenCalledOnce();
+ expect(harness.resumeHotkeys).toHaveBeenCalledOnce();
+ } finally {
+ window.removeEventListener("keydown", shortcut);
+ document.removeEventListener("paste", clipboard);
+ }
+ });
+
+ it("stays paused through retry, cancellation and output import", async () => {
+ const file = harness.files[0];
+ recordRunStart(failed(file));
+ vi.mocked(runPolicyOnFile).mockImplementationOnce(async () => {
+ recordRunStart(
+ failed(file, {
+ runId: "retry",
+ status: "PENDING",
+ startedAt: 2,
+ error: null,
+ }),
+ );
+ });
+ render(app());
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry file" })),
+ );
+ expect(runPolicyOnFile).toHaveBeenCalledWith(
+ "security",
+ "backend-security",
+ file.id,
+ file.name,
+ );
+ expect(
+ screen.getByRole("button", { name: "Retrying file..." }),
+ ).toBeDisabled();
+ act(() => updateRun("retry", { status: "CANCELLED" }));
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ act(() =>
+ recordRunStart(
+ failed(file, { runId: "success", status: "COMPLETED", startedAt: 3 }),
+ ),
+ );
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ act(() => updateRun("success", { imported: true }));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(isFileBlocked(file.id)).toBe(false);
+ });
+
+ it("retries the stored source when only a descendant remains open", async () => {
+ const original = harness.files[0];
+ recordRunStart(failed(original));
+ const child = createNewStirlingFileStub(new File(["edited"], "edited.pdf"));
+ child.sourceFileIds = [original.id];
+ child.classificationLocked = true;
+ harness.files = [child];
+ vi.mocked(fileStorage.getStirlingFileStub).mockResolvedValueOnce(original);
+ render(app());
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry file" })),
+ );
+ expect(fileStorage.getStirlingFileStub).toHaveBeenCalledWith(original.id);
+ expect(runPolicyOnFile).toHaveBeenCalledWith(
+ "security",
+ "backend-security",
+ original.id,
+ original.name,
+ );
+ });
+
+ it.each(["missing", "locked"] as const)(
+ "keeps recovery available when the stored source is %s",
+ async (state) => {
+ const file = harness.files[0];
+ recordRunStart(failed(file));
+ vi.mocked(fileStorage.getStirlingFileStub).mockResolvedValueOnce(
+ state === "missing" ? null : { ...file, classificationLocked: true },
+ );
+ render(app());
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry file" })),
+ );
+ expect(runPolicyOnFile).not.toHaveBeenCalled();
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "The action couldn't be completed. Try again.",
+ );
+ expect(screen.getByRole("button", { name: "Close file" })).toBeEnabled();
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ },
+ );
+
+ it("closes affected descendants without deleting the stored source or allowing it to reopen unblocked", async () => {
+ const original = harness.files[0];
+ recordRunStart(failed(original));
+ const child = createNewStirlingFileStub(new File(["edited"], "edited.pdf"));
+ child.sourceFileIds = [original.id];
+ harness.files = [child];
+ const view = render(app());
+ expect(isEditorPolicyBlocked()).toBe(true);
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Close file" })),
+ );
+ expect(harness.removeFiles).toHaveBeenCalledWith([child.id], false);
+ expect(harness.navigation.setSelectedTool).toHaveBeenCalledWith(null);
+ expect(harness.navigation.setWorkbench).toHaveBeenCalledWith("fileEditor");
+ harness.files = [];
+ view.rerender(app());
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(isFileBlocked(original.id)).toBe(true);
+ harness.files = [original];
+ view.rerender(app());
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ });
+
+ it("keeps the gate for the remaining failures in a batch", () => {
+ const second = createNewStirlingFileStub(new File(["pdf"], "second.pdf"));
+ harness.files.push(second);
+ harness.files.forEach((file) => recordRunStart(failed(file)));
+ render(app());
+ expect(screen.getByText("2 files affected.")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Retry 2 files" })).toBeVisible();
+ expect(screen.getAllByRole("button")).toHaveLength(2);
+ act(() =>
+ recordRunStart(
+ failed(second, {
+ runId: "success",
+ status: "COMPLETED",
+ imported: true,
+ startedAt: 2,
+ }),
+ ),
+ );
+ expect(screen.getByText("1 file affected.")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Retry file" })).toBeVisible();
+ expect(screen.getByRole("button", { name: "Close file" })).toBeVisible();
+ });
+
+ it("retries the batch once and pluralises the remaining work after partial recovery", async () => {
+ const first = harness.files[0];
+ const second = createNewStirlingFileStub(new File(["pdf"], "second.pdf"));
+ harness.files.push(second);
+ harness.files.forEach((file) => recordRunStart(failed(file)));
+ vi.mocked(runPolicyOnFile).mockImplementation(
+ async (_key, _backend, fileId) => {
+ const file = harness.files.find((file) => file.id === fileId)!;
+ recordRunStart(
+ failed(file, {
+ runId: `retry-${fileId}`,
+ status: "PENDING",
+ startedAt: 2,
+ }),
+ );
+ },
+ );
+ render(app());
+ expect(
+ screen.getByText("Contact your administrator for help."),
+ ).toBeVisible();
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry 2 files" })),
+ );
+ expect(runPolicyOnFile).toHaveBeenCalledTimes(2);
+ expect(runPolicyOnFile).toHaveBeenCalledWith(
+ "security",
+ "backend-security",
+ first.id,
+ first.name,
+ );
+ expect(runPolicyOnFile).toHaveBeenCalledWith(
+ "security",
+ "backend-security",
+ second.id,
+ second.name,
+ );
+ expect(
+ screen.getByRole("button", { name: "Retrying 2 files..." }),
+ ).toBeDisabled();
+ act(() =>
+ updateRun(`retry-${first.id}`, { status: "COMPLETED", imported: true }),
+ );
+ expect(screen.getByText("1 file affected.")).toBeVisible();
+ expect(
+ screen.getByRole("button", { name: "Retrying file..." }),
+ ).toBeDisabled();
+ act(() => updateRun(`retry-${second.id}`, { status: "FAILED" }));
+ expect(screen.getByRole("button", { name: "Retry file" })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Close file" })).toBeEnabled();
+ });
+
+ it("counts and closes each affected file once across multiple failed policies", async () => {
+ const first = harness.files[0];
+ const second = createNewStirlingFileStub(new File(["pdf"], "second.pdf"));
+ const healthy = createNewStirlingFileStub(new File(["pdf"], "healthy.pdf"));
+ harness.files.push(second, healthy);
+ updatePolicy("compliance", {
+ required: true,
+ backendId: "backend-compliance",
+ });
+ recordRunStart(failed(first));
+ recordRunStart(failed(second));
+ recordRunStart(
+ failed(first, { runId: "compliance-failure", policyKey: "compliance" }),
+ );
+ let finishClosing = () => {};
+ harness.removeFiles.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishClosing = resolve;
+ }),
+ );
+ render(app());
+ expect(screen.getByText("2 files affected.")).toBeVisible();
+ expect(screen.getAllByRole("button")).toHaveLength(2);
+ fireEvent.click(screen.getByRole("button", { name: "Close 2 files" }));
+ expect(
+ screen.getByRole("button", { name: "Closing 2 files..." }),
+ ).toBeDisabled();
+ expect(harness.removeFiles).toHaveBeenCalledOnce();
+ expect(harness.removeFiles).toHaveBeenCalledWith(
+ [first.id, second.id],
+ false,
+ );
+ await act(async () => finishClosing());
+ });
+
+ it("still retries the other files when one dispatch rejects", async () => {
+ const second = createNewStirlingFileStub(new File(["pdf"], "second.pdf"));
+ harness.files.push(second);
+ harness.files.forEach((file) => recordRunStart(failed(file)));
+ vi.mocked(runPolicyOnFile).mockRejectedValueOnce(new Error("unavailable"));
+ render(app());
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry 2 files" })),
+ );
+ expect(runPolicyOnFile).toHaveBeenCalledTimes(2);
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "The action couldn't be completed. Try again.",
+ );
+ expect(screen.getByRole("button", { name: "Retry 2 files" })).toBeEnabled();
+ });
+
+ it("does not offer a retry for a missing policy", () => {
+ updatePolicy("security", { backendId: undefined });
+ recordRunStart(failed(harness.files[0]));
+ render(app());
+ expect(screen.getByRole("button", { name: "Retry file" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Close file" })).toBeEnabled();
+ });
+
+ it("does not pause for ordinary pipeline failures or unrelated closed files", () => {
+ updatePolicy("security", { required: false });
+ recordRunStart(failed(harness.files[0]));
+ const view = render(app());
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ harness.files = [];
+ act(() => updatePolicy("security", { required: true }));
+ view.rerender(app());
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.tsx b/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.tsx
new file mode 100644
index 0000000000..3e72a9f9f8
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/PolicyRecoveryGate.tsx
@@ -0,0 +1,278 @@
+import {
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import { useAuth } from "@app/auth/UseSession";
+import { Button } from "@app/ui/Button";
+import {
+ useAllFiles,
+ useFileManagement,
+ useFileSelectors,
+} from "@app/contexts/FileContext";
+import { useHotkeys } from "@app/contexts/HotkeyContext";
+import { useNavigationActions } from "@app/contexts/NavigationContext";
+import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
+import {
+ isRunInFlight,
+ usePolicyRuns,
+ type PolicyRunRecord,
+} from "@app/components/policies/policyRunStore";
+import {
+ getWorkspacePolicyBlocks,
+ registerPolicyWorkspace,
+ subscribePolicyFileUsage,
+ policyFileUsageVersion,
+ type PolicyRecoveryBlock,
+} from "@app/services/policyBlockRegistry";
+import { loadPolicies, onPoliciesChange } from "@app/services/policyStorage";
+import { loadPolicyCatalog } from "@app/services/policyCatalog";
+import { runPolicyOnFile } from "@app/services/policyDispatch";
+import { dispatchableFileId } from "@app/components/policies/policyLocalPass";
+import { fileStorage } from "@app/services/fileStorage";
+import type { PoliciesByKey } from "@app/types/policies";
+import type { FileId } from "@app/types/file";
+import "@app/components/policies/PolicyRecoveryGate.css";
+
+/** Keeps the editor mounted but inaccessible until all open, failed inputs are recovered or closed. */
+export function PolicyRecoveryGate() {
+ const { fileStubs } = useAllFiles();
+ const selectors = useFileSelectors();
+ const runs = usePolicyRuns();
+ useSyncExternalStore(subscribePolicyFileUsage, policyFileUsageVersion);
+ const [policies, setPolicies] = useState(loadPolicies);
+ useEffect(() => onPoliciesChange(() => setPolicies(loadPolicies())), []);
+ useLayoutEffect(
+ () => registerPolicyWorkspace(selectors.getStirlingFileStubs),
+ [selectors],
+ );
+ const blocks = getWorkspacePolicyBlocks(fileStubs);
+ return blocks.length ? (
+ <RecoveryDialog blocks={blocks} policies={policies} runs={runs} />
+ ) : null;
+}
+
+interface RecoveryDialogProps {
+ blocks: PolicyRecoveryBlock[];
+ policies: PoliciesByKey;
+ runs: PolicyRunRecord[];
+}
+
+function affectedFileIds(blocks: PolicyRecoveryBlock[]): FileId[] {
+ return [
+ ...new Set(
+ blocks.flatMap((block) => block.affectedFiles.map((file) => file.id)),
+ ),
+ ];
+}
+
+function recoveryKey(block: PolicyRecoveryBlock): string {
+ return `${block.outcome.policyKey}:${block.outcome.fileId}`;
+}
+
+function RecoveryDialog({ blocks, policies, runs }: RecoveryDialogProps) {
+ const { t } = useTranslation();
+ const { user } = useAuth();
+ const titleId = useId();
+ const bodyId = useId();
+ const dialogRef = useRef<HTMLDialogElement>(null);
+ const { pauseHotkeys, resumeHotkeys, areHotkeysPaused } = useHotkeys();
+ const previouslyPaused = useRef(areHotkeysPaused);
+ const { removeFiles } = useFileManagement();
+ const { actions: navigation } = useNavigationActions();
+ const { setPreviewFile } = useToolWorkflow();
+ const [dispatching, setDispatching] = useState<Set<string>>(new Set());
+ const [closing, setClosing] = useState(false);
+ const [error, setError] = useState(false);
+ const labels = new Map(
+ loadPolicyCatalog().categories.map((category) => [
+ category.id,
+ category.label,
+ ]),
+ );
+ const fileIds = affectedFileIds(blocks);
+ const policyKeys = [
+ ...new Set(blocks.map((block) => block.outcome.policyKey)),
+ ];
+ const runningBlocks = blocks.filter(
+ (block) =>
+ dispatching.has(recoveryKey(block)) ||
+ runs.some(
+ (run) =>
+ run.fileId === block.outcome.fileId &&
+ run.policyKey === block.outcome.policyKey &&
+ run.startedAt >= block.outcome.startedAt &&
+ isRunInFlight(run),
+ ),
+ );
+ const runningFileCount = affectedFileIds(runningBlocks).length;
+ const retryable = blocks.flatMap((block) => {
+ const backendId = policies[block.outcome.policyKey]?.backendId;
+ return backendId ? [{ block, backendId }] : [];
+ });
+ const retryFileCount = affectedFileIds(
+ retryable.map(({ block }) => block),
+ ).length;
+ const policyName = (key: string) =>
+ policies[key]?.name ?? labels.get(key) ?? key;
+
+ useLayoutEffect(() => {
+ const dialog = dialogRef.current;
+ if (!dialog) return;
+ const previousFocus = document.activeElement;
+ // The top layer also makes existing portals inert; a z-index overlay cannot do that.
+ dialog.showModal();
+ pauseHotkeys();
+ const stopEvent = (event: Event) => event.stopPropagation();
+ // Keep dialog events out of editor handlers without cancelling browser or clipboard defaults.
+ for (const name of ["keydown", "keyup", "copy", "cut", "paste"])
+ dialog.addEventListener(name, stopEvent);
+ return () => {
+ for (const name of ["keydown", "keyup", "copy", "cut", "paste"])
+ dialog.removeEventListener(name, stopEvent);
+ dialog.close();
+ if (!previouslyPaused.current) resumeHotkeys();
+ if (previousFocus instanceof HTMLElement && previousFocus.isConnected)
+ previousFocus.focus();
+ };
+ }, [pauseHotkeys, resumeHotkeys]);
+
+ const retry = async () => {
+ if (runningFileCount || closing) return;
+ setDispatching(new Set(retryable.map(({ block }) => recoveryKey(block))));
+ setError(false);
+ const results = await Promise.allSettled(
+ retryable.map(async ({ block, backendId }) => {
+ const { fileId, policyKey, fileName } = block.outcome;
+ try {
+ // The failed source can be closed while its descendants remain open.
+ const source = await fileStorage.getStirlingFileStub(
+ fileId as FileId,
+ );
+ const target = source ? dispatchableFileId(source) : null;
+ if (!target) throw new Error("Policy source cannot be retried");
+ await runPolicyOnFile(
+ policyKey,
+ backendId,
+ target,
+ fileName ?? block.affectedFiles[0].name,
+ );
+ } finally {
+ setDispatching((previous) => {
+ const next = new Set(previous);
+ next.delete(recoveryKey(block));
+ return next;
+ });
+ }
+ }),
+ );
+ setError(results.some((result) => result.status === "rejected"));
+ };
+
+ const closeFiles = async () => {
+ if (closing) return;
+ setClosing(true);
+ setError(false);
+ try {
+ // End the tool session so retained comparison slots and previews cannot keep using the input.
+ navigation.setSelectedTool(null);
+ navigation.setWorkbench("fileEditor");
+ setPreviewFile(null);
+ await removeFiles(fileIds, false);
+ } catch {
+ setError(true);
+ } finally {
+ setClosing(false);
+ }
+ };
+
+ return createPortal(
+ <dialog
+ ref={dialogRef}
+ className="policy-recovery"
+ aria-labelledby={titleId}
+ aria-describedby={bodyId}
+ onCancel={(event) => event.preventDefault()}
+ >
+ <h2 id={titleId}>{t("policy.recoveryTitle")}</h2>
+ <p id={bodyId}>
+ {t("policy.recoverySummary", { count: fileIds.length })}
+ </p>
+ {error && <p role="alert">{t("policy.recoveryError")}</p>}
+ <div className="policy-recovery__policies">
+ {policyKeys.map((policyKey) => {
+ const policy = policies[policyKey];
+ const owner = policy?.owner?.trim();
+ const isOwner = Boolean(
+ owner &&
+ !user?.is_anonymous &&
+ (owner === user?.username ||
+ owner.toLowerCase() === user?.email?.toLowerCase()),
+ );
+ return (
+ <section className="policy-recovery__policy" key={policyKey}>
+ <strong>{policyName(policyKey)}</strong>
+ <p className="policy-recovery__hint">
+ {t(
+ isOwner
+ ? "policy.recoveryOwnedPolicy"
+ : owner
+ ? "policy.recoveryContactOwner"
+ : "policy.recoveryContactAdmin",
+ { owner },
+ )}
+ </p>
+ </section>
+ );
+ })}
+ </div>
+ <details className="policy-recovery__details">
+ <summary>{t("policy.recoveryTechnicalDetails")}</summary>
+ <div className="policy-recovery__errors">
+ {blocks.map((block) => (
+ <div className="policy-recovery__error" key={recoveryKey(block)}>
+ <strong>
+ {block.outcome.fileName ?? block.affectedFiles[0].name}
+ </strong>
+ {policyKeys.length > 1 && (
+ <p>{policyName(block.outcome.policyKey)}</p>
+ )}
+ {block.outcome.error && <pre>{block.outcome.error}</pre>}
+ </div>
+ ))}
+ </div>
+ </details>
+ <div className="policy-recovery__actions">
+ <Button
+ variant="primary"
+ disabled={runningFileCount > 0 || closing || retryable.length === 0}
+ onClick={() => void retry()}
+ >
+ {t(
+ runningFileCount
+ ? "policy.recoveryRetrying"
+ : "policy.recoveryRetry",
+ {
+ count: runningFileCount || retryFileCount || fileIds.length,
+ },
+ )}
+ </Button>
+ <Button
+ variant="secondary"
+ disabled={closing}
+ onClick={() => void closeFiles()}
+ >
+ {t(closing ? "policy.recoveryClosing" : "policy.recoveryClose", {
+ count: fileIds.length,
+ })}
+ </Button>
+ </div>
+ </dialog>,
+ document.body,
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/README.md b/frontend/editor/src/proprietary/components/policies/README.md
index 19e2b8567e..c98f552490 100644
--- a/frontend/editor/src/proprietary/components/policies/README.md
+++ b/frontend/editor/src/proprietary/components/policies/README.md
@@ -9,6 +9,17 @@ the core (OSS) build has no implementation (`usePoliciesEnabled` stub = false),
and desktop additionally requires an active SaaS connection (runs bill through
the cloud). The single gate is `components/policies/usePoliciesEnabled.ts`.
+A required upload-policy failure pauses the entire editor with `PolicyRecoveryGate`.
+The modal keeps editor state mounted, makes the background inert, and pauses editor
+shortcuts while preserving browser commands. Retry stays blocked until the policy output is imported; closing the affected
+files ends the current tool session and retains the originals in the library. Failures
+persist separately from the capped activity log, including through cancellation and reload.
+Ordinary pipeline failures do not pause the editor.
+Required export-policy failures cancel that export without freezing further editing.
+
+The gate includes open derivatives and files retained by Compare outside the workspace.
+Operation, download and upload boundaries recheck failures after asynchronous preparation.
+
## Layout
| Path | Role |
@@ -19,7 +30,7 @@ the cloud). The single gate is `components/policies/usePoliciesEnabled.ts`.
| `hooks/usePolicies.ts` | Policy state + permission flag, consumed by the auto-run controller. |
| `hooks/usePolicyFileBadges.ts` | Per-file badge map (which policies produced/are enforcing a file) — drives the shared `PolicyBadges` row and the exit-point blocking. |
| `components/policies/usePoliciesEnabled.ts` | The single build/connection gate for mounting the auto-run controller. Core stub = false; desktop shadow adds the SaaS-connection check. |
-| `components/policies/PolicyAutoRunController.tsx` | Headless: enforces enabled policies on every uploaded file. Mounted by `RightSidebar`. |
+| `components/policies/PolicyAutoRunController.tsx` | Runs policies and recovery once per editor. Mounted by `HomePage`, outside the tool sidebar. |
| `components/policies/usePolicyAutoRun.ts` | The auto-run engine: dispatch, polling, retry, output import, server reconcile. |
| `components/policies/policyRunStore.ts` | `useSyncExternalStore` store of run records (status, progress, outputs), persisted to localStorage. |
| `components/policies/enforcementQueue.ts` | Export-time enforcement queue used by `services/policyExport.ts`. |
diff --git a/frontend/editor/src/proprietary/components/policies/policyRunStore.test.ts b/frontend/editor/src/proprietary/components/policies/policyRunStore.test.ts
index 5a099e62c4..e566d9c784 100644
--- a/frontend/editor/src/proprietary/components/policies/policyRunStore.test.ts
+++ b/frontend/editor/src/proprietary/components/policies/policyRunStore.test.ts
@@ -3,6 +3,7 @@ import {
appliedPoliciesFor,
dispatchKey,
getRun,
+ getPolicyRunOutcomes,
isDispatched,
markDispatched,
recordRunStart,
@@ -218,6 +219,76 @@ describe("policyRunStore", () => {
expect(runs.some((r: PolicyRunRecord) => r.runId === "r0")).toBe(false); // oldest dropped
});
+ it("retains a failed outcome after its run is evicted and storage is reloaded", () => {
+ recordRunStart(rec({ runId: "failed", status: "FAILED" }));
+ for (let i = 0; i < 200; i++) {
+ recordRunStart(
+ rec({
+ runId: `other-${i}`,
+ fileId: `other-${i}`,
+ status: "COMPLETED",
+ imported: true,
+ startedAt: i + 2,
+ }),
+ );
+ }
+ expect(getRun("failed")).toBeUndefined();
+ const saved = localStorage.getItem("stirling-policy-runs")!;
+ resetPolicyRuns();
+ localStorage.setItem("stirling-policy-runs", saved);
+ window.dispatchEvent(
+ new StorageEvent("storage", { key: "stirling-policy-runs" }),
+ );
+
+ expect(getPolicyRunOutcomes()[dispatchKey("security", "f1")]?.status).toBe(
+ "FAILED",
+ );
+ });
+
+ it("keeps a failure through retry-record removal and cancellation until a successful retry", () => {
+ recordRunStart(rec({ runId: "failed", status: "FAILED" }));
+ removeRun("failed");
+ recordRunStart(rec({ runId: "retry", startedAt: 2 }));
+ updateRun("retry", { status: "CANCELLED" });
+ expect(getPolicyRunOutcomes()[dispatchKey("security", "f1")]?.status).toBe(
+ "FAILED",
+ );
+
+ recordRunStart(rec({ runId: "success", startedAt: 3 }));
+ updateRun("success", { status: "COMPLETED" });
+ expect(getPolicyRunOutcomes()[dispatchKey("security", "f1")]?.status).toBe(
+ "FAILED",
+ );
+ updateRun("success", { imported: true });
+ expect(getPolicyRunOutcomes()[dispatchKey("security", "f1")]?.status).toBe(
+ "COMPLETED",
+ );
+
+ updateRun("retry", { status: "FAILED" });
+ expect(getPolicyRunOutcomes()[dispatchKey("security", "f1")]?.status).toBe(
+ "COMPLETED",
+ );
+ });
+
+ it("migrates legacy history without allowing a cancelled retry to clear a failure", () => {
+ localStorage.setItem(
+ "stirling-policy-runs",
+ JSON.stringify({
+ runs: [
+ rec({ runId: "retry", startedAt: 2, status: "CANCELLED" }),
+ rec({ runId: "failed", status: "FAILED" }),
+ ],
+ dispatched: [],
+ }),
+ );
+ window.dispatchEvent(
+ new StorageEvent("storage", { key: "stirling-policy-runs" }),
+ );
+ expect(getPolicyRunOutcomes()[dispatchKey("security", "f1")]?.status).toBe(
+ "FAILED",
+ );
+ });
+
it("does not evict a COMPLETED run that hasn't been imported yet, even past the cap", () => {
for (let i = 0; i < 210; i++) {
recordRunStart(
diff --git a/frontend/editor/src/proprietary/components/policies/policyRunStore.ts b/frontend/editor/src/proprietary/components/policies/policyRunStore.ts
index e5e26b1a32..5092e97b53 100644
--- a/frontend/editor/src/proprietary/components/policies/policyRunStore.ts
+++ b/frontend/editor/src/proprietary/components/policies/policyRunStore.ts
@@ -60,9 +60,20 @@ export const POLICY_IN_FLIGHT_STATUSES: readonly PolicyRunStatus[] = [
"WAITING_FOR_INPUT",
];
+/** Latest definitive result per policy/file, retained independently of the activity log. */
+export interface PolicyRunOutcome {
+ policyKey: string;
+ fileId: string;
+ fileName?: string;
+ error?: string | null;
+ status: "COMPLETED" | "FAILED";
+ startedAt: number;
+}
+
interface RunState {
runs: PolicyRunRecord[];
dispatched: string[];
+ outcomes: Record<string, PolicyRunOutcome>;
/** startedAt of the run that began the current processing "wave" — a burst of
* runs with no idle gap. Reset whenever a run is recorded while nothing is in
* flight. The panel's progress counts (X of Y processed) scope to this so they
@@ -114,6 +125,38 @@ function capRuns(runs: PolicyRunRecord[]): PolicyRunRecord[] {
return trimmed;
}
+function recordOutcome(
+ outcomes: Record<string, PolicyRunOutcome>,
+ run: PolicyRunRecord,
+): Record<string, PolicyRunOutcome> {
+ // Success releases a failed input only after its replacement or labels have been imported.
+ if (
+ !run.fileId ||
+ run.browserLocal ||
+ (run.status !== "FAILED" && !(run.status === "COMPLETED" && run.imported))
+ )
+ return outcomes;
+ const key = dispatchKey(run.policyKey, run.fileId);
+ const previous = outcomes[key];
+ if (
+ previous &&
+ (previous.startedAt > run.startedAt ||
+ (previous.startedAt === run.startedAt && previous.status === run.status))
+ )
+ return outcomes;
+ return {
+ ...outcomes,
+ [key]: {
+ policyKey: run.policyKey,
+ fileId: run.fileId,
+ fileName: run.fileName,
+ error: run.error,
+ status: run.status,
+ startedAt: run.startedAt,
+ },
+ };
+}
+
function read(): RunState {
try {
const raw =
@@ -122,10 +165,10 @@ function read(): RunState {
: null;
if (raw) {
const parsed = JSON.parse(raw) as Partial<RunState>;
- return {
+ const runs: PolicyRunRecord[] =
// Normalise older persisted records (which predate the `outputs` field)
// so consumers can always rely on `outputs` being an array.
- runs: Array.isArray(parsed.runs)
+ Array.isArray(parsed.runs)
? parsed.runs.map((r) => ({
...r,
// Records written before the rename carry the key as `categoryId`. Without this
@@ -139,7 +182,11 @@ function read(): RunState {
// Records predating per-run targets all executed on SaaS.
target: r.target === "local" ? "local" : "saas",
}))
- : [],
+ : [];
+ return {
+ runs,
+ // Seed older caches from their remaining history; newer caches retain outcomes after pruning.
+ outcomes: runs.reduce(recordOutcome, parsed.outcomes ?? {}),
dispatched: Array.isArray(parsed.dispatched) ? parsed.dispatched : [],
waveStartedAt:
typeof parsed.waveStartedAt === "number" ? parsed.waveStartedAt : 0,
@@ -148,7 +195,7 @@ function read(): RunState {
} catch {
// Corrupt/unavailable storage — start empty.
}
- return { runs: [], dispatched: [], waveStartedAt: 0 };
+ return { runs: [], dispatched: [], outcomes: {}, waveStartedAt: 0 };
}
let state: RunState = read();
@@ -192,6 +239,7 @@ function getSnapshot(): RunState {
const SERVER_SNAPSHOT: RunState = {
runs: [],
dispatched: [],
+ outcomes: {},
waveStartedAt: 0,
};
function getServerSnapshot(): RunState {
@@ -247,6 +295,7 @@ export function recordRunStart(record: PolicyRunRecord) {
: record.startedAt;
state = {
runs: capRuns([record, ...state.runs]),
+ outcomes: recordOutcome(state.outcomes, record),
dispatched: state.dispatched.includes(key)
? state.dispatched
: [...state.dispatched, key],
@@ -263,11 +312,15 @@ export function recordRunStart(record: PolicyRunRecord) {
*/
export function addReconciledRun(record: PolicyRunRecord) {
if (state.runs.some((r) => r.runId === record.runId)) return;
- state = { ...state, runs: capRuns([record, ...state.runs]) };
+ state = {
+ ...state,
+ runs: capRuns([record, ...state.runs]),
+ outcomes: recordOutcome(state.outcomes, record),
+ };
emit();
}
-/** Mark a (policy, file) pair dispatched without a run (e.g. dispatch failed). */
+/** Mark a (policy, file) pair handled without a run, such as a file with no remaining bytes. */
export function markDispatched(policyKey: string, fileId: string) {
const key = dispatchKey(policyKey, fileId);
if (state.dispatched.includes(key)) return;
@@ -278,13 +331,16 @@ export function markDispatched(policyKey: string, fileId: string) {
/** Patch an in-flight run's status/outputs/error as it progresses. */
export function updateRun(runId: string, patch: Partial<PolicyRunRecord>) {
let changed = false;
+ let outcomes = state.outcomes;
const runs = state.runs.map((r) => {
if (r.runId !== runId) return r;
changed = true;
- return { ...r, ...patch };
+ const updated = { ...r, ...patch };
+ outcomes = recordOutcome(outcomes, updated);
+ return updated;
});
if (!changed) return;
- state = { ...state, runs };
+ state = { ...state, runs, outcomes };
emit();
}
@@ -303,10 +359,17 @@ export function removeRun(runId: string) {
/** Reset the store — used by tests to isolate it. */
export function resetPolicyRuns() {
- state = { runs: [], dispatched: [], waveStartedAt: 0 };
+ state = { runs: [], dispatched: [], outcomes: {}, waveStartedAt: 0 };
emit();
}
+/** Synchronous enforcement state, available before the editor's effects mount. */
+export function getPolicyRunOutcomes(): Readonly<
+ Record<string, PolicyRunOutcome>
+> {
+ return state.outcomes;
+}
+
export function usePolicyRuns(): PolicyRunRecord[] {
return useSyncExternalStore(
subscribe,
diff --git a/frontend/editor/src/proprietary/services/policyBackend.test.ts b/frontend/editor/src/proprietary/services/policyBackend.test.ts
index cc64445bee..7f4235b466 100644
--- a/frontend/editor/src/proprietary/services/policyBackend.test.ts
+++ b/frontend/editor/src/proprietary/services/policyBackend.test.ts
@@ -17,6 +17,7 @@ const policy = (
) => ({
id,
name: id,
+ owner: "[email protected]",
enabled: true,
inputs: [],
steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
@@ -116,6 +117,7 @@ describe("decodedToState — runsOnEditor", () => {
);
expect(state.runsOnEditor).toBe(true);
+ expect(state.owner).toBe("[email protected]");
});
// Participation is the policy's own flag now, so a tile that never opted in does not run in the
diff --git a/frontend/editor/src/proprietary/services/policyBackend.ts b/frontend/editor/src/proprietary/services/policyBackend.ts
index c58d6c569c..c35649dd33 100644
--- a/frontend/editor/src/proprietary/services/policyBackend.ts
+++ b/frontend/editor/src/proprietary/services/policyBackend.ts
@@ -50,8 +50,10 @@ export function decodedToState(
configured: true,
enabled: decoded.enabled,
name: decoded.name,
+ owner: decoded.owner,
sources: decoded.sources,
runsOnEditor: decoded.runsOnEditor,
+ required: decoded.required,
scopeTypes: decoded.scopeTypes,
reviewerEmail: decoded.reviewerEmail,
fieldValues: decoded.fieldValues,
diff --git a/frontend/editor/src/proprietary/services/policyBlockRegistry.ts b/frontend/editor/src/proprietary/services/policyBlockRegistry.ts
new file mode 100644
index 0000000000..2e3e4ccb56
--- /dev/null
+++ b/frontend/editor/src/proprietary/services/policyBlockRegistry.ts
@@ -0,0 +1,96 @@
+import {
+ getPolicyRunOutcomes,
+ type PolicyRunOutcome,
+} from "@app/components/policies/policyRunStore";
+import { loadPolicies } from "@app/services/policyStorage";
+import { policySourceIds } from "@core/services/policyBlockRegistry";
+import type { StirlingFileStub } from "@app/types/fileContext";
+export { policySourceIds };
+
+/** A failed policy and the open documents derived from its input. */
+export interface PolicyRecoveryBlock {
+ outcome: PolicyRunOutcome;
+ affectedFiles: StirlingFileStub[];
+}
+
+let readWorkspace: () => StirlingFileStub[] = () => [];
+const fileUsages = new Map<symbol, StirlingFileStub[]>();
+const usageListeners = new Set<() => void>();
+let usageVersion = 0;
+
+/** Register documents retained outside the workspace until their owning tool releases them. */
+export function registerPolicyFileUsage(files: StirlingFileStub[]): () => void {
+ const owner = Symbol();
+ const emit = () => {
+ usageVersion += 1;
+ usageListeners.forEach((listener) => listener());
+ };
+ fileUsages.set(owner, files);
+ emit();
+ return () => {
+ fileUsages.delete(owner);
+ emit();
+ };
+}
+
+/** Subscribe to retained-document changes, independently of policy polling. */
+export function subscribePolicyFileUsage(listener: () => void): () => void {
+ usageListeners.add(listener);
+ return () => {
+ usageListeners.delete(listener);
+ };
+}
+
+/** Stable external-store snapshot for retained-document registrations. */
+export function policyFileUsageVersion(): number {
+ return usageVersion;
+}
+
+/** Bind the mounted editor's live selectors; cleanup releases its document references. */
+export function registerPolicyWorkspace(
+ read: () => StirlingFileStub[],
+): () => void {
+ readWorkspace = read;
+ return () => {
+ if (readWorkspace === read) readWorkspace = () => [];
+ };
+}
+
+/** Durable failures remain blocking through retries, cancellation and activity-log eviction. */
+export function getWorkspacePolicyBlocks(
+ files = readWorkspace(),
+): PolicyRecoveryBlock[] {
+ const policies = loadPolicies();
+ const openFiles = [
+ ...new Map(
+ [...files, ...Array.from(fileUsages.values()).flat()].map((file) => [
+ file.id,
+ file,
+ ]),
+ ).values(),
+ ];
+ return Object.values(getPolicyRunOutcomes()).flatMap((outcome) => {
+ if (outcome.status !== "FAILED" || !policies[outcome.policyKey]?.required)
+ return [];
+ const affectedFiles = openFiles.filter((file) =>
+ policySourceIds(file).includes(outcome.fileId),
+ );
+ return affectedFiles.length ? [{ outcome, affectedFiles }] : [];
+ });
+}
+
+/** Read the durable result, including for files closed out of the workspace. */
+export function isFileBlocked(fileId: string): boolean {
+ const policies = loadPolicies();
+ return Object.values(getPolicyRunOutcomes()).some(
+ (outcome) =>
+ outcome.fileId === fileId &&
+ outcome.status === "FAILED" &&
+ policies[outcome.policyKey]?.required,
+ );
+}
+
+/** Checks live file state and outcomes without waiting for a React effect. */
+export function isEditorPolicyBlocked(): boolean {
+ return getWorkspacePolicyBlocks().length > 0;
+}
diff --git a/frontend/editor/src/proprietary/services/policyDispatch.test.ts b/frontend/editor/src/proprietary/services/policyDispatch.test.ts
new file mode 100644
index 0000000000..f86b0f173f
--- /dev/null
+++ b/frontend/editor/src/proprietary/services/policyDispatch.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { runPolicyOnFile } from "@app/services/policyDispatch";
+import { runStoredPolicy } from "@app/services/policyApi";
+import { fileStorage } from "@app/services/fileStorage";
+import { isFileBlocked } from "@app/services/policyBlockRegistry";
+import * as runStore from "@app/components/policies/policyRunStore";
+import {
+ createNewStirlingFileStub,
+ createStirlingFile,
+} from "@app/types/fileContext";
+import { dispatchableFileId } from "@app/components/policies/policyLocalPass";
+
+vi.mock("@app/services/policyApi", () => ({
+ runStoredPolicy: vi.fn(),
+ resolvePolicyRunTarget: () => "local",
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { getStirlingFile: vi.fn(), getStirlingFileStub: vi.fn() },
+}));
+
+const file = new File(["%PDF"], "doc.pdf", { type: "application/pdf" });
+const stub = createNewStirlingFileStub(file);
+const fileId = dispatchableFileId(stub)!;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1000);
+ localStorage.clear();
+ runStore.resetPolicyRuns();
+ localStorage.setItem(
+ "stirling-policies-state",
+ JSON.stringify({ security: { required: true } }),
+ );
+ vi.mocked(fileStorage.getStirlingFile).mockResolvedValue(
+ createStirlingFile(file, fileId),
+ );
+ vi.mocked(fileStorage.getStirlingFileStub).mockResolvedValue(stub);
+ vi.mocked(runStoredPolicy).mockReset();
+});
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe("upload-policy dispatch failures", () => {
+ it("records request failure as a durable block with recovery after a successful retry", async () => {
+ const recorded = vi.spyOn(runStore, "recordRunStart");
+ vi.mocked(runStoredPolicy).mockRejectedValueOnce(
+ new Error("Backend offline"),
+ );
+ await runPolicyOnFile("security", "backend", fileId, "doc.pdf");
+
+ expect(recorded).toHaveBeenCalledWith(
+ expect.objectContaining({
+ runId: expect.stringMatching(/^dispatch-failed:/),
+ status: "FAILED",
+ fileId,
+ policyKey: "security",
+ error: "Backend offline",
+ target: "local",
+ }),
+ );
+ expect(runStore.isDispatched("security", fileId)).toBe(true);
+ expect(isFileBlocked(fileId)).toBe(true);
+ const saved = localStorage.getItem("stirling-policy-runs")!;
+ runStore.resetPolicyRuns();
+ localStorage.setItem("stirling-policy-runs", saved);
+ window.dispatchEvent(
+ new StorageEvent("storage", { key: "stirling-policy-runs" }),
+ );
+ expect(isFileBlocked(fileId)).toBe(true);
+
+ vi.setSystemTime(2000);
+ vi.mocked(runStoredPolicy).mockResolvedValueOnce("retry");
+ await runPolicyOnFile("security", "backend", fileId, "doc.pdf");
+ expect(isFileBlocked(fileId)).toBe(true);
+ runStore.updateRun("retry", { status: "COMPLETED", imported: true });
+ expect(isFileBlocked(fileId)).toBe(false);
+ });
+
+ it("records an optional pipeline failure without blocking the file", async () => {
+ localStorage.setItem(
+ "stirling-policies-state",
+ JSON.stringify({ security: { required: false } }),
+ );
+ vi.mocked(runStoredPolicy).mockRejectedValueOnce(
+ new Error("Backend offline"),
+ );
+ await runPolicyOnFile("security", "backend", fileId, "doc.pdf");
+ expect(
+ runStore.getPolicyRunOutcomes()[runStore.dispatchKey("security", fileId)]
+ ?.status,
+ ).toBe("FAILED");
+ expect(isFileBlocked(fileId)).toBe(false);
+ });
+
+ it("does not let an older request failing late override a newer successful attempt", async () => {
+ vi.mocked(runStoredPolicy)
+ .mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ setTimeout(() => reject(new Error("Request timed out")), 1000);
+ }),
+ )
+ .mockResolvedValueOnce("retry");
+ const older = runPolicyOnFile("security", "backend", fileId, "doc.pdf");
+ await vi.advanceTimersByTimeAsync(1);
+ await runPolicyOnFile("security", "backend", fileId, "doc.pdf");
+ runStore.updateRun("retry", { status: "COMPLETED", imported: true });
+ await vi.runAllTimersAsync();
+ await older;
+ expect(isFileBlocked(fileId)).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/proprietary/services/policyDispatch.ts b/frontend/editor/src/proprietary/services/policyDispatch.ts
index 2d56208246..f1771446f6 100644
--- a/frontend/editor/src/proprietary/services/policyDispatch.ts
+++ b/frontend/editor/src/proprietary/services/policyDispatch.ts
@@ -19,6 +19,8 @@ import {
} from "@app/components/policies/policyRunStore";
import type { DispatchableFileId } from "@app/components/policies/policyLocalPass";
import type { StirlingFile } from "@app/types/fileContext";
+import { extractErrorMessage } from "@app/utils/toolErrorHandler";
+import { generateId } from "@app/utils/generateId";
/** Wait for an upload's bytes to land in IndexedDB (~5s): the stub surfaces in the
* file list before its bytes are committed, so an eager fetch would miss the file. */
@@ -27,7 +29,7 @@ const FILE_WAIT_MS = 250;
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
-/** Resolve the file's bytes, fire a backend run, and record it. */
+/** Dispatch a file and record the attempt, including request failures so required policies block it. */
export async function runPolicyOnFile(
policyKey: string,
backendId: string,
@@ -72,9 +74,10 @@ export async function runPolicyOnFile(
}
// Bounded upload window — see MAX_CONCURRENT_DISPATCHES. Only the POST is
// gated; the IDB wait above never holds a slot.
+ const target = resolvePolicyRunTarget();
await acquireDispatchSlot(priority);
+ const startedAt = Date.now();
try {
- const target = resolvePolicyRunTarget();
// Recorded against a document this browser can resolve. One file per run, which is the only
// shape the server keeps a reference for.
const runId = await runStoredPolicy(backendId, [file], fileId);
@@ -89,17 +92,27 @@ export async function runPolicyOnFile(
status: "PENDING",
outputs: [],
error: null,
- startedAt: Date.now(),
+ startedAt,
});
} catch (err) {
- // Dispatch failed (e.g. policy deleted/404 or backend offline). Mark dispatched so we don't hammer;
- // the absent run simply won't appear in the activity feed. If the backend did
- // start a run we never recorded, reconcileServerRuns rediscovers it.
+ // No server run ID is available. The terminal local record blocks required-policy inputs
+ // and exposes manual recovery without sending status polls for an invented server run.
+ recordRunStart({
+ runId: `dispatch-failed:${generateId()}`,
+ policyKey,
+ fileId,
+ fileName,
+ fileSize: file.size,
+ target,
+ status: "FAILED",
+ outputs: [],
+ error: extractErrorMessage(err),
+ startedAt,
+ });
console.debug(
`[PolicyAutoRun] Failed to dispatch policy ${policyKey} (${backendId}):`,
err,
);
- markDispatched(policyKey, fileId);
} finally {
releaseDispatchSlot();
}
diff --git a/frontend/editor/src/proprietary/services/policyExport.test.ts b/frontend/editor/src/proprietary/services/policyExport.test.ts
index e2b28c69d0..d0794c64be 100644
--- a/frontend/editor/src/proprietary/services/policyExport.test.ts
+++ b/frontend/editor/src/proprietary/services/policyExport.test.ts
@@ -25,6 +25,7 @@ vi.mock("@app/services/policyApi", () => ({
vi.mock("@app/components/policies/policyRunStore", () => ({
recordRunStart: vi.fn(),
isDispatched: () => false,
+ getPolicyRunOutcomes: () => ({}),
}));
// Run the queued task inline: the queue's own behaviour is not under test here.
vi.mock("@app/components/policies/enforcementQueue", () => ({
@@ -126,6 +127,51 @@ describe("export-time policy selection", () => {
expect(runStoredPolicy).not.toHaveBeenCalled();
});
+ it("refuses export when a required policy fails", async () => {
+ loadPolicies.mockReturnValue({
+ security: exportPolicy({ runsOnEditor: true, required: true }),
+ });
+ runStoredPolicy.mockRejectedValueOnce(new Error("offline"));
+ await expect(enforceExportPolicies([pdf()], ["file-1"])).rejects.toThrow(
+ "policy.exportBlocked",
+ );
+ });
+
+ it("still enforces a later required policy after an optional failure", async () => {
+ loadPolicies.mockReturnValue({
+ optional: exportPolicy({
+ runsOnEditor: true,
+ backendId: "optional",
+ order: 0,
+ }),
+ required: exportPolicy({
+ runsOnEditor: true,
+ backendId: "required",
+ required: true,
+ order: 1,
+ }),
+ });
+ runStoredPolicy.mockRejectedValueOnce(new Error("offline"));
+ const enforcement = enforceExportPolicies([pdf()], ["file-1"]);
+ await vi.runAllTimersAsync();
+ await enforcement;
+ expect(runStoredPolicy.mock.calls.map(([id]) => id)).toEqual([
+ "optional",
+ "required",
+ ]);
+ });
+
+ it("still allows the original when an ordinary pipeline fails", async () => {
+ loadPolicies.mockReturnValue({
+ security: exportPolicy({ runsOnEditor: true, required: false }),
+ });
+ runStoredPolicy.mockRejectedValueOnce(new Error("offline"));
+ const input = pdf();
+ await expect(enforceExportPolicies([input], ["file-1"])).resolves.toEqual([
+ input,
+ ]);
+ });
+
it("enforces an editor pipeline set to run on export", async () => {
loadPolicies.mockReturnValue({
"builder-1": exportPolicy({
diff --git a/frontend/editor/src/proprietary/services/policyExport.ts b/frontend/editor/src/proprietary/services/policyExport.ts
index b328fd438b..f13c2ca197 100644
--- a/frontend/editor/src/proprietary/services/policyExport.ts
+++ b/frontend/editor/src/proprietary/services/policyExport.ts
@@ -4,13 +4,14 @@
* what gets exported. Core export handlers reach this via the `@app/*` alias
* (the open-source build ships a no-op stub).
*
- * Export is never hard-blocked: on failure the original file is exported and a
- * warning toast is shown. For "new version" policies, the run is also recorded
+ * Required-policy failures cancel the export; ordinary pipeline failures warn.
+ * For "new version" policies, the run is also recorded
* so the mounted import effect versions the in-editor file, not just the
* download. Each policy selects files using its first step's accepted inputs.
*/
import { loadPolicies } from "@app/services/policyStorage";
+import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
import { loadPolicyCatalog } from "@app/services/policyCatalog";
import { policyAcceptsFile } from "@app/services/policyInput";
import { splitFileName } from "@app/utils/fileUtils";
@@ -46,6 +47,7 @@ interface ExportPolicy extends Pick<PolicyState, "firstOperation"> {
backendId: string;
label: string;
outputMode: "new_file" | "new_version";
+ required: boolean;
/** The policy's accent as a CSS colour, for the toast glow. */
accent: string;
}
@@ -82,6 +84,7 @@ function activeExportPolicies(): ExportPolicy[] {
// A builder pipeline has no built-in category, so it labels by its own name.
label: labels.get(id) ?? s.name ?? "Policy",
outputMode: s.outputMode === "new_file" ? "new_file" : "new_version",
+ required: s.required === true,
accent: `var(--color-${ROW_ACCENT[id] ?? "blue"})`,
}))
);
@@ -141,7 +144,7 @@ function enforcedFilesSummary(names: string[]): string {
/**
* Enforce compatible active export policies just before export, returning
- * the files in order (enforced, or the original on failure). `fileIds[i]` is the
+ * the files in order; required failures throw before export. `fileIds[i]` is the
* workspace id of `files[i]` when known — used to version the in-editor file for
* "new version" policies. Incompatible files pass through untouched, and a single toast
* (glowing in the policy's accent while it runs) fades a few seconds after the
@@ -152,6 +155,7 @@ export async function enforceExportPolicies(
fileIds?: (string | undefined)[],
trigger: EnforcementTrigger = "export",
): Promise<File[]> {
+ assertFilesNotBlocked(fileIds);
const active = activeExportPolicies();
if (!active.length || files.length === 0) return files;
@@ -174,7 +178,8 @@ export async function enforceExportPolicies(
// Serialise through the enforcement queue: one policy run in flight at a time
// (the backend rejects concurrent runs under load), and the user can see
// what's pending. Export, print and convert all share this queue.
- return runQueued({ label: names, trigger }, async () => {
+ const enforced = await runQueued({ label: names, trigger }, async () => {
+ assertFilesNotBlocked(fileIds);
// An earlier queued job may have just enforced these same files and marked
// them dispatched, so re-check at run time before doing (or announcing) work.
if (!targets.some(hasCompatiblePolicy)) return files;
@@ -202,22 +207,32 @@ export async function enforceExportPolicies(
const out = [...files];
let failures = 0;
+ let requiredFailure = false;
let done = 0;
for (const i of pending) {
const file = files[i];
const fileId = fileIds?.[i];
const toRun = pendingFor(fileId);
+ let runningPolicy: ExportPolicy | undefined;
try {
let current = file;
+ let optionalFailure = false;
// The last "new version" policy's output is what versions the editor
// file (recording every policy would double-consume the same input).
let versionRun: (PolicyRunResult & { policyKey: string }) | undefined;
for (const policy of toRun) {
if (!policyAcceptsFile(policy, current)) continue;
- const result = await runToCompletion(policy.backendId, current);
- current = result.file;
- if (policy.outputMode === "new_version" && fileId) {
- versionRun = { ...result, policyKey: policy.policyKey };
+ runningPolicy = policy;
+ try {
+ const result = await runToCompletion(policy.backendId, current);
+ current = result.file;
+ if (policy.outputMode === "new_version" && fileId) {
+ versionRun = { ...result, policyKey: policy.policyKey };
+ }
+ } catch (error) {
+ if (policy.required) throw error;
+ // An optional failure must not skip a required policy later in the chain.
+ optionalFailure = true;
}
}
const [base, inputExtension] = splitFileName(file.name);
@@ -247,8 +262,10 @@ export async function enforceExportPolicies(
startedAt: Date.now(),
});
}
+ if (optionalFailure) failures += 1;
} catch {
- failures += 1; // leave out[i] as the original — never hard-block.
+ failures += 1;
+ if (runningPolicy?.required) requiredFailure = true;
}
}
@@ -258,10 +275,12 @@ export async function enforceExportPolicies(
? {
alertType: "warning",
title: i18n.t("policies.enforcement.failureTitle"),
- body: i18n.t("policies.enforcement.failureBody", {
- failures,
- total,
- }),
+ body: requiredFailure
+ ? i18n.t("policy.exportBlocked")
+ : i18n.t("policies.enforcement.failureBody", {
+ failures,
+ total,
+ }),
isPersistentPopup: false,
glowColor: undefined,
}
@@ -275,6 +294,9 @@ export async function enforceExportPolicies(
);
// update() doesn't reschedule auto-dismiss, so fade the result out explicitly.
window.setTimeout(() => dismissToast(toastId), TOAST_LINGER_MS);
+ if (requiredFailure) throw new Error(i18n.t("policy.exportBlocked"));
return out;
});
+ assertFilesNotBlocked(fileIds);
+ return enforced;
}
diff --git a/frontend/editor/src/proprietary/services/policyPipeline.ts b/frontend/editor/src/proprietary/services/policyPipeline.ts
index c8399f7803..752abffb2f 100644
--- a/frontend/editor/src/proprietary/services/policyPipeline.ts
+++ b/frontend/editor/src/proprietary/services/policyPipeline.ts
@@ -44,7 +44,7 @@ export interface BackendPolicy {
/** Blank on create — the backend assigns an id and returns it. */
id: string;
name: string;
- owner: string;
+ owner: string | null;
/** Gates automatic triggering; an explicit run ignores it. */
enabled: boolean;
/** Null for a manual-only (client-driven) policy — the editor fires runs on
@@ -54,6 +54,8 @@ export interface BackendPolicy {
output: BackendOutputSpec;
/** Whether the editor runs this policy per file, and on which moment. */
editor?: BackendEditorConfig;
+ /** A policy (blocking on failure) rather than an ordinary pipeline; see Policy.required. */
+ required?: boolean;
}
/** Mirrors the backend `EditorConfig`. */
@@ -115,12 +117,16 @@ export interface DecodedPolicy {
/** The policy this record belongs to, read from `output.options.categoryId`. */
policyKey: string;
name: string;
+ /** The backend owner's username; empty when no owner is assigned. */
+ owner: string;
enabled: boolean;
/** Null if the stored policy carried no automation blob. */
automation: AutomationConfig | null;
sources: string[];
/** Whether the editor runs this policy per file, straight from the policy's own flag. */
runsOnEditor: boolean;
+ /** A policy (blocking on failure) rather than an ordinary pipeline (see Policy.required). */
+ required: boolean;
scopeTypes: string[];
reviewerEmail: string;
fieldValues: Record<string, boolean | string | string[]>;
@@ -158,6 +164,7 @@ export function fromBackendPolicy(policy: BackendPolicy): DecodedPolicy {
firstOperation && isToolEndpoint(firstOperation) ? firstOperation : null,
policyKey,
name: policy.name,
+ owner: str(policy.owner),
enabled: policy.enabled,
automation: (output.automation as AutomationConfig | undefined) ?? null,
sources: Array.isArray(meta.sources) ? (meta.sources as string[]) : [],
@@ -168,6 +175,7 @@ export function fromBackendPolicy(policy: BackendPolicy): DecodedPolicy {
fieldValues:
(meta.fieldValues as DecodedPolicy["fieldValues"] | undefined) ?? {},
runsOnEditor: editor?.allowed === true,
+ required: policy.required === true,
folder: {
runOn: resolveRunOn(editor?.runOn, policyKey),
// Legacy/missing output.mode defaults to new_version, not new_file.
diff --git a/frontend/editor/src/proprietary/services/policyRecoveryGuards.test.ts b/frontend/editor/src/proprietary/services/policyRecoveryGuards.test.ts
new file mode 100644
index 0000000000..39dfc25c6a
--- /dev/null
+++ b/frontend/editor/src/proprietary/services/policyRecoveryGuards.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ createNewStirlingFileStub,
+ createStirlingFile,
+ type StirlingFileStub,
+} from "@app/types/fileContext";
+import {
+ recordRunStart,
+ resetPolicyRuns,
+} from "@app/components/policies/policyRunStore";
+import { registerPolicyWorkspace } from "@app/services/policyBlockRegistry";
+import {
+ PolicyBlockedError,
+ assertFilesNotBlocked,
+} from "@app/services/policyFileGuard";
+import { updatePolicy } from "@app/services/policyStorage";
+import { downloadFile } from "@app/services/downloadService";
+import { uploadHistoryChain } from "@app/services/serverStorageUpload";
+import { fileStorage } from "@app/services/fileStorage";
+import { buildHistoryBundle } from "@app/services/serverStorageBundle";
+import apiClient from "@app/services/apiClient";
+
+vi.mock("@app/services/apiClient", () => ({
+ default: { post: vi.fn(), put: vi.fn() },
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { getHistoryChainStubs: vi.fn(), getStirlingFile: vi.fn() },
+}));
+vi.mock("@app/services/serverStorageBundle", () => ({
+ buildHistoryBundle: vi.fn(),
+}));
+vi.mock("@app/i18n", () => ({ default: { t: (key: string) => key } }));
+
+let files: StirlingFileStub[];
+let unregister: () => void;
+let source: StirlingFileStub;
+const pdf = new File(["pdf"], "file.pdf", { type: "application/pdf" });
+
+function fail() {
+ recordRunStart({
+ runId: "failure",
+ policyKey: "security",
+ fileId: source.id,
+ fileName: source.name,
+ fileSize: 3,
+ target: "local",
+ status: "FAILED",
+ error: "offline",
+ outputs: [],
+ startedAt: 1,
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ resetPolicyRuns();
+ updatePolicy("security", { required: true });
+ source = createNewStirlingFileStub(pdf);
+ files = [source];
+ unregister = registerPolicyWorkspace(() => files);
+});
+afterEach(() => {
+ unregister();
+ vi.restoreAllMocks();
+});
+
+describe("policy recovery boundaries", () => {
+ it("blocks immediately, including downloads without a source id", async () => {
+ const click = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(() => {});
+ fail();
+ expect(() => assertFilesNotBlocked()).toThrow(PolicyBlockedError);
+ await expect(
+ downloadFile({ data: pdf, filename: pdf.name }),
+ ).rejects.toThrow(PolicyBlockedError);
+ expect(click).not.toHaveBeenCalled();
+ files = [];
+ expect(() => assertFilesNotBlocked()).not.toThrow();
+ await expect(
+ downloadFile({ data: pdf, filename: pdf.name, fileId: source.id }),
+ ).rejects.toThrow(PolicyBlockedError);
+ });
+
+ it("blocks an open derivative even after the failed input was consumed", () => {
+ const child = createNewStirlingFileStub(pdf);
+ child.sourceFileIds = [source.id];
+ files = [child];
+ fail();
+ expect(() => assertFilesNotBlocked()).toThrow(PolicyBlockedError);
+ });
+
+ it("refuses a server upload when a policy fails while its bundle is being prepared", async () => {
+ vi.mocked(fileStorage.getHistoryChainStubs).mockResolvedValue([source]);
+ vi.mocked(fileStorage.getStirlingFile).mockResolvedValue(
+ createStirlingFile(pdf, source.id),
+ );
+ vi.mocked(buildHistoryBundle).mockImplementationOnce(async () => {
+ fail();
+ // Closing the source while preparation finishes must not authorize its captured bytes.
+ files = [];
+ return { bundleFile: pdf, manifest: {} } as Awaited<
+ ReturnType<typeof buildHistoryBundle>
+ >;
+ });
+ await expect(uploadHistoryChain(source.id)).rejects.toThrow(
+ PolicyBlockedError,
+ );
+ expect(apiClient.post).not.toHaveBeenCalled();
+ expect(apiClient.put).not.toHaveBeenCalled();
+ });
+
+ it("allows ordinary pipeline failures to continue", () => {
+ updatePolicy("security", { required: false });
+ fail();
+ expect(() => assertFilesNotBlocked([source.id])).not.toThrow();
+ });
+});
diff --git a/frontend/editor/src/proprietary/types/policies.ts b/frontend/editor/src/proprietary/types/policies.ts
index 9e8e404e4a..24df76fe48 100644
--- a/frontend/editor/src/proprietary/types/policies.ts
+++ b/frontend/editor/src/proprietary/types/policies.ts
@@ -46,8 +46,15 @@ export interface PolicyState {
sources: string[];
/** The policy's own name. Set for builder pipelines, which have no built-in category label. */
name?: string;
+ /** The owner's username (email on SaaS), used to direct recovery requests. */
+ owner?: string;
/** Whether the policy runs in the editor as each file passes through (resolved at decode). */
runsOnEditor?: boolean;
+ /**
+ * A policy (blocking) rather than an ordinary pipeline: when it fails on an editor file the file
+ * is blocked (unusable), whereas a pipeline failure only warns. See the pipeline `Policy.required`.
+ */
+ required?: boolean;
/** When non-empty, narrows the policy to these document types. */
scopeTypes: string[];
/** Email that low-confidence enforcements are routed to. */