Skip to content

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

Avoid running tools on files they're incompatible with (#7873)

James Bruntone0101058b899
diff --git a/app/common/src/main/java/stirling/software/common/config/swagger/ToolIOOperationCustomizer.java b/app/common/src/main/java/stirling/software/common/config/swagger/ToolIOOperationCustomizer.java
index b5c3a3ef87..38938b2929 100644
--- a/app/common/src/main/java/stirling/software/common/config/swagger/ToolIOOperationCustomizer.java
+++ b/app/common/src/main/java/stirling/software/common/config/swagger/ToolIOOperationCustomizer.java
@@ -4,8 +4,11 @@ import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import javax.imageio.ImageIO;
+
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springdoc.core.customizers.GlobalOperationCustomizer;
import org.springframework.stereotype.Component;
@@ -41,6 +44,11 @@ public class ToolIOOperationCustomizer
public void customise(OpenAPI openApi) {
Map<String, Object> vocabulary = new LinkedHashMap<>();
vocabulary.put("formats", names(ToolFormat.values()));
+ Map<String, List<String>> extensions = new LinkedHashMap<>();
+ for (ToolFormat format : ToolFormat.values()) {
+ extensions.put(format.name(), format.getExtensions());
+ }
+ vocabulary.put("extensions", extensions);
vocabulary.put("arities", names(ToolArity.values()));
openApi.addExtension(VOCABULARY_EXTENSION_NAME, vocabulary);
}
@@ -61,6 +69,20 @@ public class ToolIOOperationCustomizer
extension.put("accepts", names(declaration.accepts()));
extension.put("produces", declaration.produces().name());
extension.put("arity", declaration.arity().name());
+ if (declaration.imageIOInput()) {
+ extension.put(
+ "inputExtensions",
+ Arrays.stream(ImageIO.getReaderFileSuffixes())
+ .map(suffix -> suffix.toLowerCase(Locale.ROOT))
+ // The raw reader requires dimensions supplied out of band, not an
+ // uploaded file.
+ .filter(suffix -> !suffix.equals("raw"))
+ .distinct()
+ .sorted()
+ .toList());
+ } else if (declaration.inputExtensions().length > 0) {
+ extension.put("inputExtensions", List.of(declaration.inputExtensions()));
+ }
if (declaration.cases().length > 0) {
extension.put("cases", cases(declaration, handler));
}
diff --git a/app/common/src/main/java/stirling/software/common/model/tool/ToolIO.java b/app/common/src/main/java/stirling/software/common/model/tool/ToolIO.java
index 30325b4b62..9a3bc6d279 100644
--- a/app/common/src/main/java/stirling/software/common/model/tool/ToolIO.java
+++ b/app/common/src/main/java/stirling/software/common/model/tool/ToolIO.java
@@ -21,6 +21,12 @@ public @interface ToolIO {
/** Defaulting to a plain PDF is what makes an ordinary endpoint reject an encrypted one. */
ToolFormat[] accepts() default {ToolFormat.PDF};
+ /** Filename suffixes when the input parser accepts less or more than the format categories. */
+ String[] inputExtensions() default {};
+
+ /** Derive input suffixes from the installed ImageIO readers used by the endpoint. */
+ boolean imageIOInput() default false;
+
ToolFormat produces();
ToolArity arity() default ToolArity.SISO;
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
index c7799497a5..536d0562ef 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
@@ -44,6 +44,7 @@ public class ConvertHtmlToPDF {
// A ZIP of HTML plus its CSS is a first-class input here, and is what convert/pdf/html emits.
@ToolIO(
accepts = {ToolFormat.HTML, ToolFormat.ZIP},
+ inputExtensions = {"html", "zip"},
produces = ToolFormat.PDF)
@Operation(
summary = "Convert an HTML or ZIP (containing HTML and CSS) to PDF",
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
index 80a129ce99..309ce4ee5a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
@@ -266,7 +266,11 @@ public class ConvertImgPDFController {
value = "/img/pdf",
resourceWeight = ResourceWeight.LARGE_WEIGHT)
@StandardPdfResponse
- @ToolIO(accepts = ToolFormat.IMAGE, produces = ToolFormat.PDF, arity = ToolArity.MISO)
+ @ToolIO(
+ accepts = ToolFormat.IMAGE,
+ imageIOInput = true,
+ produces = ToolFormat.PDF,
+ arity = ToolArity.MISO)
@Operation(
summary = "Convert images to a PDF file",
description =
@@ -298,7 +302,10 @@ public class ConvertImgPDFController {
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/cbz/pdf",
resourceWeight = ResourceWeight.MEDIUM_WEIGHT)
- @ToolIO(accepts = ToolFormat.CBZ, produces = ToolFormat.PDF)
+ @ToolIO(
+ accepts = ToolFormat.CBZ,
+ inputExtensions = {"cbz", "zip"},
+ produces = ToolFormat.PDF)
@Operation(
summary = "Convert CBZ comic book archive to PDF",
description = "This endpoint converts a CBZ (ZIP) comic book archive to a PDF file.")
@@ -351,7 +358,10 @@ public class ConvertImgPDFController {
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/cbr/pdf",
resourceWeight = ResourceWeight.MEDIUM_WEIGHT)
- @ToolIO(accepts = ToolFormat.CBR, produces = ToolFormat.PDF)
+ @ToolIO(
+ accepts = ToolFormat.CBR,
+ inputExtensions = {"cbr", "rar"},
+ produces = ToolFormat.PDF)
@Operation(
summary = "Convert CBR comic book archive to PDF",
description = "This endpoint converts a CBR (RAR) comic book archive to a PDF file.")
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java
index c9c95d6ef2..7ff61533da 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java
@@ -52,6 +52,7 @@ public class ConvertMarkdownToPdf {
// A ZIP of Markdown plus its images is a first-class input here, not just a bare .md file.
@ToolIO(
accepts = {ToolFormat.MARKDOWN, ToolFormat.ZIP},
+ inputExtensions = {"md", "zip"},
produces = ToolFormat.PDF)
@Operation(
summary = "Convert a Markdown file to PDF",
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java
index 0b1bfc8e44..5018de308f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java
@@ -57,6 +57,7 @@ public class ConvertSvgToPDF {
@MultiFileResponse
@ToolIO(
accepts = ToolFormat.IMAGE,
+ inputExtensions = "svg",
produces = ToolFormat.PDF,
arity = ToolArity.MIMO,
cases =
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
index ef1202a6f9..6b665ba969 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
@@ -66,7 +66,15 @@ public class ExtractImageScansController {
value = "/extract-image-scans",
resourceWeight = ResourceWeight.LARGE_WEIGHT)
@MultiFileResponse
- @ToolIO(produces = ToolFormat.IMAGE, arity = ToolArity.SIMO)
+ // split_photos.py uses OpenCV imread, which cannot read the vector/PSD formats in IMAGE.
+ @ToolIO(
+ accepts = {ToolFormat.PDF, ToolFormat.IMAGE},
+ inputExtensions = {
+ "pdf", "bmp", "dib", "gif", "jpeg", "jpg", "jpe", "jp2", "png", "webp", "avif",
+ "pbm", "pgm", "ppm", "pxm", "pnm", "pfm", "sr", "ras", "tiff", "tif", "hdr", "pic"
+ },
+ produces = ToolFormat.IMAGE,
+ arity = ToolArity.SIMO)
@Operation(
summary = "Extract image scans from an input file",
description =
diff --git a/app/core/src/test/java/stirling/software/SPDF/config/ToolIOInputExtensionsTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ToolIOInputExtensionsTest.java
new file mode 100644
index 0000000000..fd2cc424a1
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/config/ToolIOInputExtensionsTest.java
@@ -0,0 +1,62 @@
+package stirling.software.SPDF.config;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.springframework.web.method.HandlerMethod;
+
+import io.swagger.v3.oas.models.Operation;
+
+import stirling.software.common.config.swagger.ToolIOOperationCustomizer;
+
+class ToolIOInputExtensionsTest {
+ @ParameterizedTest
+ @CsvSource(
+ delimiter = ';',
+ value = {
+ "ConvertSvgToPDF;convertSvgToPdf;svg",
+ "ConvertHtmlToPDF;HtmlToPdf;html,zip",
+ "ConvertMarkdownToPdf;markdownToPdf;md,zip",
+ "ConvertImgPDFController;convertCbzToPdf;cbz,zip",
+ "ConvertImgPDFController;convertCbrToPdf;cbr,rar"
+ })
+ void converterRestrictionsOverrideBroadCategories(
+ String controller, String method, String suffixes) throws Exception {
+ assertEquals(List.of(suffixes.split(",")), inputExtensions(controller, method));
+ }
+
+ @Test
+ void imageInputsFollowTheInstalledReaders() throws Exception {
+ List<?> extensions = inputExtensions("ConvertImgPDFController", "convertToPdf");
+ assertTrue(
+ extensions.containsAll(
+ List.of("png", "jpg", "jpeg", "tiff", "webp", "psd", "wbmp")));
+ assertFalse(extensions.contains("ai"));
+ assertFalse(extensions.contains("eps"));
+ assertFalse(extensions.contains("raw"));
+ }
+
+ private static List<?> inputExtensions(String controller, String methodName) throws Exception {
+ Class<?> type =
+ Class.forName("stirling.software.SPDF.controller.api.converters." + controller);
+ Method method =
+ Arrays.stream(type.getMethods())
+ .filter(candidate -> candidate.getName().equals(methodName))
+ .findFirst()
+ .orElseThrow();
+ Operation operation =
+ new ToolIOOperationCustomizer()
+ .customize(new Operation(), new HandlerMethod(type, method));
+ Map<?, ?> declaration = (Map<?, ?>) operation.getExtensions().get("x-stirling-io");
+ return (List<?>) declaration.get("inputExtensions");
+ }
+}
diff --git a/engine/src/stirling/models/tool_io.py b/engine/src/stirling/models/tool_io.py
index c9da9cce90..f8cf47f6c6 100644
--- a/engine/src/stirling/models/tool_io.py
+++ b/engine/src/stirling/models/tool_io.py
@@ -222,7 +222,7 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {
accepts=[ToolFormat.PDF], produces=ToolFormat.ZIP, arity=ToolArity.SISO
),
ToolEndpoint.EXTRACT_IMAGE_SCANS: ToolIOSpec(
- accepts=[ToolFormat.PDF], produces=ToolFormat.IMAGE, arity=ToolArity.SIMO
+ accepts=[ToolFormat.PDF, ToolFormat.IMAGE], produces=ToolFormat.IMAGE, arity=ToolArity.SIMO
),
ToolEndpoint.EXTRACT_IMAGES: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.IMAGE, arity=ToolArity.SIMO),
ToolEndpoint.FLATTEN: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 7de2a50931..ec5fc30abe 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -34,8 +34,6 @@ downloadUnavailable = "Download unavailable for this item"
edit = "Edit"
editSecret = "Edit this value"
editYourNewFiles = "Edit your new file(s)"
-encryptedFilesBlocked_one = "File is password-protected. Unlock it first."
-encryptedFilesBlocked_other = "{{count}} files are password-protected. Unlock them first."
exportAndContinue = "Export & Continue"
false = "False"
fileNotSavedToDisk = "Not saved to disk"
@@ -4233,6 +4231,7 @@ versionHistory = "Version history"
[files]
addFiles = "Add files"
created = "Created"
+notIncludedInToolRun = "Not included in this tool run"
selectFromWorkbench = "Add files to the workbench or "
selectMultipleFromWorkbench = "Add at least {{count}} files to the workbench or "
size = "File Size"
diff --git a/frontend/editor/scripts/generate-tool-api-types.mts b/frontend/editor/scripts/generate-tool-api-types.mts
index ec38dc37d7..ac570748fd 100644
--- a/frontend/editor/scripts/generate-tool-api-types.mts
+++ b/frontend/editor/scripts/generate-tool-api-types.mts
@@ -256,6 +256,9 @@ export type ToolFormat = ${union(formats)};
/** Every format, for iteration. */
export const TOOL_FORMATS = ${JSON.stringify(formats)} as const satisfies readonly ToolFormat[];
+/** Filename extensions from the backend ToolFormat declarations. */
+export const TOOL_FORMAT_EXTENSIONS: Record<ToolFormat, readonly string[]> = ${JSON.stringify(vocabulary.extensions)};
+
/** How many files go in and come out. A multi-output tool returns its results zipped, and the caller unpacks them. */
export type ToolArity = ${union(vocabulary.arities as string[])};
@@ -277,6 +280,8 @@ export interface ToolIOCase {
/** What one endpoint accepts and produces. */
export interface ToolIOSpec {
accepts: ToolFormat[];
+ /** Overrides the broad format categories for filename-based input checks. */
+ inputExtensions?: string[];
produces: ToolFormat;
arity: ToolArity;
cases?: ToolIOCase[];
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
index 1201402bf7..8256f187ea 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
@@ -86,6 +86,15 @@
box-shadow: var(--shadow-lg);
}
+.card[data-tool-skipped="true"] .thumbContainer {
+ opacity: 0.45;
+ filter: grayscale(1);
+}
+
+.card[data-tool-skipped="true"] .fileNameText {
+ color: var(--c-text-muted);
+}
+
.thumbImage {
width: 100%;
height: 100%;
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
index d0a87d8221..da218584d2 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -52,6 +52,7 @@ import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbn
import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
import { truncateCenter } from "@app/utils/textUtils";
import { FileEditorStatusDot } from "@app/components/fileEditor/FileEditorStatusDot";
+import { useToolEligibleFileIds } from "@app/contexts/ToolFileEligibilityContext";
interface FileEditorThumbnailProps {
file: StirlingFileStub;
@@ -82,6 +83,12 @@ const FileEditorThumbnail = ({
policies = [],
}: FileEditorThumbnailProps) => {
const { t } = useTranslation();
+ const eligibleFileIds = useToolEligibleFileIds();
+ const isToolSkipped =
+ eligibleFileIds !== null && !eligibleFileIds.has(file.id);
+ const toolSkipReason = isToolSkipped
+ ? t("files.notIncludedInToolRun", "Not included in this tool run")
+ : undefined;
const { config } = useAppConfig();
const terminology = useFileActionTerminology();
const icons = useFileActionIcons();
@@ -511,6 +518,9 @@ const FileEditorThumbnail = ({
data-testid="file-thumbnail"
data-tour="file-card-checkbox"
data-supported={isSupported}
+ data-tool-skipped={isToolSkipped}
+ title={toolSkipReason}
+ aria-description={toolSkipReason}
className={`${styles.card} select-none`}
style={{ opacity: isDragging ? 0.9 : 1 }}
tabIndex={0}
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index bb9afc5dc9..5fa5e7cb27 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -75,6 +75,7 @@ import {
} from "@app/components/watchedFolders/watchedFolderDragState";
import { WATCHED_FOLDERS_ENABLED } from "@app/constants/featureFlags";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
+import { useToolEligibleFileIds } from "@app/contexts/ToolFileEligibilityContext";
import "@app/components/shared/FileSidebar.css";
// Shared with the processor sidebar via tokens, so the two cannot drift.
@@ -834,6 +835,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
!isGoogleDriveEnabled && config?.hideDisabledToolsGoogleDrive;
const width = collapsed ? COLLAPSED_WIDTH : EXPANDED_WIDTH;
+ const eligibleFileIds = useToolEligibleFileIds();
// Render one file row (shared by the flat list and the grouped SaaS layout).
const renderFileRow = (stub: StirlingFileStub) => {
@@ -885,6 +887,12 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
: lineageKey;
return (
<FileItem
+ isToolSkipped={
+ isInWorkbench &&
+ !isWatchedFoldersActive &&
+ eligibleFileIds !== null &&
+ !eligibleFileIds.has(stub.id)
+ }
key={rowKey}
fileId={stub.id}
name={stub.name}
diff --git a/frontend/editor/src/core/components/shared/FileSidebarFileItem.css b/frontend/editor/src/core/components/shared/FileSidebarFileItem.css
index bfabe83544..587779b874 100644
--- a/frontend/editor/src/core/components/shared/FileSidebarFileItem.css
+++ b/frontend/editor/src/core/components/shared/FileSidebarFileItem.css
@@ -68,6 +68,17 @@
background-color: color-mix(in srgb, var(--c-primary) 6%, transparent);
}
+.file-sidebar-file-item[data-tool-skipped="true"] {
+ background-color: var(--c-surface-sunken);
+}
+
+.file-sidebar-file-item[data-tool-skipped="true"]
+ .file-sidebar-file-icon-wrapper,
+.file-sidebar-file-item[data-tool-skipped="true"] .file-sidebar-file-info {
+ opacity: 0.5;
+ filter: grayscale(1);
+}
+
/* Icon wrapper */
.file-sidebar-file-icon-wrapper {
position: relative;
diff --git a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
index a6d0e19514..71b1182971 100644
--- a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
@@ -142,6 +142,7 @@ export interface FileItemProps {
isSelected: boolean;
isActive: boolean;
isViewedInViewer: boolean;
+ isToolSkipped?: boolean;
thumbnailUrl?: string;
onClick: (fileId: FileId) => void;
onEyeClick: (fileId: FileId, e: React.MouseEvent) => void;
@@ -234,6 +235,7 @@ export const FileItem = React.memo(function FileItem({
isSelected,
isActive,
isViewedInViewer,
+ isToolSkipped = false,
dataUnavailable,
thumbnailUrl,
onClick,
@@ -256,6 +258,9 @@ export const FileItem = React.memo(function FileItem({
hasVersionHistory = false,
}: FileItemProps) {
const { t } = useTranslation();
+ const toolSkipReason = isToolSkipped
+ ? t("files.notIncludedInToolRun", "Not included in this tool run")
+ : undefined;
const terminology = useFileActionTerminology();
const DownloadIcon = useFileActionIcons().download;
const ext = getFileExtension(name);
@@ -336,6 +341,9 @@ export const FileItem = React.memo(function FileItem({
<>
<div
ref={itemRef}
+ data-tool-skipped={isToolSkipped}
+ title={toolSkipReason}
+ aria-description={toolSkipReason}
className={`file-sidebar-file-item${isSelected ? " selected" : ""}${isActive ? " active" : ""}${isViewedInViewer ? " viewed" : ""}`}
onClick={() => onClick(fileId)}
draggable={draggable}
diff --git a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
index 4b03de0a4b..fd025cf503 100644
--- a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
+++ b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
@@ -14,6 +14,7 @@ import { StirlingFile } from "@app/types/fileContext";
import type { TooltipTip } from "@app/types/tips";
import type { ExecuteDisabledReason } from "@app/hooks/tools/shared/toolOperationTypes";
import classes from "@app/components/tools/shared/createToolFlow.module.css";
+import { ToolFileEligibility } from "@app/contexts/ToolFileEligibilityContext";
export interface FilesStepConfig {
selectedFiles: StirlingFile[];
@@ -103,6 +104,13 @@ export function createToolFlow<TParams = unknown>(
return (
<Stack gap="sm" p="sm">
+ <ToolFileEligibility
+ files={
+ config.files.isVisible === false || config.review.isVisible
+ ? null
+ : config.files.selectedFiles
+ }
+ />
{/* <Stack gap="sm" p="sm" h="100%" w="100%" style={{ overflow: 'auto' }}> */}
<ToolStepProvider forceStepNumbers={config.forceStepNumbers}>
{config.title && <ToolWorkflowTitle {...config.title} />}
@@ -141,7 +149,9 @@ export function createToolFlow<TParams = unknown>(
config.executeButton.isVisible !== false &&
(() => {
const eb = config.executeButton;
- const hasFiles = (config.files.selectedFiles?.length ?? 0) > 0;
+ const hasFiles =
+ (config.files.selectedFiles?.length ?? 0) >=
+ (config.files.minFiles ?? 1);
// Compute the disabled reason from structured fields; explicit disabledReason wins if set.
const effectiveDisabledReason: ExecuteDisabledReason =
eb.disabledReason !== undefined
diff --git a/frontend/editor/src/core/contexts/ToolFileEligibilityContext.tsx b/frontend/editor/src/core/contexts/ToolFileEligibilityContext.tsx
new file mode 100644
index 0000000000..dfb14b857c
--- /dev/null
+++ b/frontend/editor/src/core/contexts/ToolFileEligibilityContext.tsx
@@ -0,0 +1,57 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useState,
+} from "react";
+import type { ReactNode } from "react";
+import type { FileId, StirlingFile } from "@app/types/fileContext";
+
+type EligibleFileIds = ReadonlySet<FileId> | null;
+
+const EligibleFileIdsContext = createContext<EligibleFileIds>(null);
+const RegisterEligibilityContext = createContext<
+ (ids: EligibleFileIds) => () => void
+>(() => () => {});
+
+/** Shares the mounted tool's eligible files with workbench and sidebar previews. */
+export function ToolFileEligibilityProvider({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const [eligibleFileIds, setEligibleFileIds] = useState<EligibleFileIds>(null);
+ const register = useCallback((ids: EligibleFileIds) => {
+ setEligibleFileIds(ids);
+ return () =>
+ setEligibleFileIds((current) => (current === ids ? null : current));
+ }, []);
+
+ return (
+ <RegisterEligibilityContext.Provider value={register}>
+ <EligibleFileIdsContext.Provider value={eligibleFileIds}>
+ {children}
+ </EligibleFileIdsContext.Provider>
+ </RegisterEligibilityContext.Provider>
+ );
+}
+
+/** Publishes the Files step's selection until it unmounts; null clears dimming. */
+export function ToolFileEligibility({
+ files,
+}: {
+ files: readonly StirlingFile[] | null;
+}) {
+ const register = useContext(RegisterEligibilityContext);
+ useEffect(
+ () => register(files && new Set(files.map((file) => file.fileId))),
+ [files, register],
+ );
+ return null;
+}
+
+/** Null means no tool selection is active, so file previews should remain undimmed. */
+export function useToolEligibleFileIds(): EligibleFileIds {
+ return useContext(EligibleFileIdsContext);
+}
diff --git a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
index df75ec1808..30fda73ace 100644
--- a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
+++ b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
@@ -41,6 +41,7 @@ import {
import type { ToolPanelMode } from "@app/constants/toolPanel";
import { usePreferences } from "@app/contexts/PreferencesContext";
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
+import { ToolFileEligibilityProvider } from "@app/contexts/ToolFileEligibilityContext";
// State interface
// Types and reducer/state moved to './toolWorkflow/state'
@@ -808,7 +809,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
<ToolWorkflowActionsContext.Provider value={actionsValue}>
<ToolWorkflowDataContext.Provider value={dataValue}>
<ToolWorkflowContext.Provider value={contextValue}>
- {children}
+ <ToolFileEligibilityProvider>{children}</ToolFileEligibilityProvider>
</ToolWorkflowContext.Provider>
</ToolWorkflowDataContext.Provider>
</ToolWorkflowActionsContext.Provider>
diff --git a/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.ts b/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.ts
index 6cbe97428b..f40b6f0730 100644
--- a/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.ts
@@ -384,6 +384,12 @@ export interface ToolOperationHook<TParams = void> {
willUseCloud?: boolean;
// Actions
+ /** Non-empty inputs accepted for the current params, using FileContext's protection metadata.
+ * Operations with their own execution path can omit this to retain their own selection rules. */
+ getEligibleFiles?: (
+ params: TParams,
+ selectedFiles: StirlingFile[],
+ ) => StirlingFile[];
executeOperation: (
params: TParams,
selectedFiles: StirlingFile[],
diff --git a/frontend/editor/src/core/hooks/tools/shared/useBaseTool.ts b/frontend/editor/src/core/hooks/tools/shared/useBaseTool.ts
index df21dc3b3b..610b77af60 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useBaseTool.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useBaseTool.ts
@@ -85,7 +85,10 @@ export function useBaseTool<
useEndpointEnabled(params.getEndpointName());
// Standard computed state - defined early so it's available in useEffects
- const hasFiles = effectiveFiles.length >= minFiles;
+ const selectedFiles =
+ operation.getEligibleFiles?.(params.parameters, effectiveFiles) ??
+ effectiveFiles;
+ const hasFiles = selectedFiles.length >= minFiles;
const hasResults =
operation.files.length > 0 || operation.downloadUrl !== null;
const settingsCollapsed = !hasFiles || hasResults;
@@ -145,6 +148,7 @@ export function useBaseTool<
// Standard handlers
const handleExecute = useCallback(async () => {
+ if (!hasFiles) return;
try {
await operation.executeOperation(params.parameters, effectiveFiles);
if (operation.files && onComplete) {
@@ -163,6 +167,7 @@ export function useBaseTool<
operation,
params.parameters,
effectiveFiles,
+ hasFiles,
onComplete,
onError,
toolName,
@@ -189,7 +194,7 @@ export function useBaseTool<
return {
// File management
- selectedFiles: effectiveFiles,
+ selectedFiles,
// Tool-specific hooks
params,
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
index 295f6c9084..fddcb49788 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { useFileContext } from "@app/contexts/FileContext";
import { useNavigationActions } from "@app/contexts/NavigationContext";
import { ViewerContext } from "@app/contexts/ViewerContext";
+import { toolAcceptsFile } from "@app/utils/toolIOCompat";
import { useToolState } from "@app/hooks/tools/shared/useToolState";
import {
useToolApiCalls,
@@ -181,6 +182,41 @@ export const useToolOperation = <TParams>(
[config.operationType, config.toolType, notificationsAvailable],
);
+ const getCompatibleFiles = useCallback(
+ (params: TParams, selectedFiles: StirlingFile[]) => {
+ const endpoint =
+ typeof config.endpoint === "function"
+ ? config.endpoint(params)
+ : config.endpoint;
+ return selectedFiles.filter((file) =>
+ toolAcceptsFile(
+ endpoint ?? undefined,
+ selectors.getStirlingFileStub(file.fileId) ?? file,
+ ),
+ );
+ },
+ [config.endpoint, selectors],
+ );
+
+ const eligibleFilesRef = useRef<StirlingFile[]>([]);
+ const getEligibleFiles = useCallback(
+ (params: TParams, selectedFiles: StirlingFile[]) => {
+ const eligibleFiles = getCompatibleFiles(params, selectedFiles).filter(
+ (file) => file.size > 0,
+ );
+ const previous = eligibleFilesRef.current;
+ if (
+ eligibleFiles.length === previous.length &&
+ eligibleFiles.every((file, index) => file === previous[index])
+ ) {
+ return previous;
+ }
+ eligibleFilesRef.current = eligibleFiles;
+ return eligibleFiles;
+ },
+ [getCompatibleFiles],
+ );
+
const executeOperation = useCallback(
async (params: TParams, selectedFiles: StirlingFile[]): Promise<void> => {
// Validation
@@ -189,8 +225,16 @@ export const useToolOperation = <TParams>(
return;
}
+ const runtimeEndpoint: string | undefined = config.endpoint
+ ? typeof config.endpoint === "function"
+ ? (config.endpoint(params) ?? undefined)
+ : config.endpoint
+ : undefined;
+
+ const compatibleFiles = getCompatibleFiles(params, selectedFiles);
+
// Handle zero-byte inputs explicitly: mark as error and continue with others
- const zeroByteFiles = selectedFiles.filter((file) => file.size === 0);
+ const zeroByteFiles = compatibleFiles.filter((file) => file.size === 0);
if (zeroByteFiles.length > 0) {
try {
for (const f of zeroByteFiles) {
@@ -200,7 +244,7 @@ export const useToolOperation = <TParams>(
console.log("markFileError", e);
}
}
- const validFiles: StirlingFile[] = selectedFiles.filter(
+ const validFiles: StirlingFile[] = compatibleFiles.filter(
(file) => file.size > 0,
);
if (validFiles.length === 0) {
@@ -208,35 +252,6 @@ export const useToolOperation = <TParams>(
return;
}
- // Block encrypted files from being sent to backend tools
- const encryptedFiles = validFiles.filter((f) => {
- const stub = selectors.getStirlingFileStub(f.fileId);
- return stub?.processedFile?.isEncrypted === true;
- });
- if (encryptedFiles.length > 0) {
- for (const ef of encryptedFiles) {
- fileActions.openEncryptedUnlockPrompt(ef.fileId);
- }
- actions.setError(
- t(
- "encryptedFilesBlocked",
- "{{count}} files are password-protected. Unlock them first.",
- {
- count: encryptedFiles.length,
- },
- ),
- );
- return;
- }
-
- // Resolve the runtime endpoint from params (static string or function result).
- // Custom processors may omit endpoint entirely — result is undefined in that case.
- const runtimeEndpoint: string | undefined = config.endpoint
- ? typeof config.endpoint === "function"
- ? (config.endpoint(params) ?? undefined)
- : config.endpoint
- : undefined;
-
// Credit check — no-op in core builds, real check in desktop/SaaS versions.
// Pass runtime endpoint so the check can determine if this routes locally (no credits needed).
const creditError = await checkCredits(runtimeEndpoint);
@@ -709,6 +724,8 @@ export const useToolOperation = <TParams>(
t,
config,
actions,
+ selectors,
+ fileActions,
addFiles,
consumeFiles,
navActions,
@@ -722,6 +739,7 @@ export const useToolOperation = <TParams>(
continueResolutions,
notificationsAvailable,
reportFailure,
+ getCompatibleFiles,
],
);
@@ -829,6 +847,7 @@ export const useToolOperation = <TParams>(
willUseCloud,
// Actions
+ getEligibleFiles,
executeOperation,
resetResults,
clearError: actions.clearError,
diff --git a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
new file mode 100644
index 0000000000..d08af30655
--- /dev/null
+++ b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
@@ -0,0 +1,485 @@
+import { createContext, type ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { render, renderHook, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { MantineProvider } from "@mantine/core";
+import Compress from "@app/tools/Compress";
+import Convert from "@app/tools/Convert";
+import Merge from "@app/tools/Merge";
+import ScannerImageSplit from "@app/tools/ScannerImageSplit";
+import ConvertToPdfUaSettings from "@app/components/tools/convert/ConvertToPdfUaSettings";
+import type { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
+import type { ToolAutomationSettingsProps } from "@app/hooks/tools/shared/toolOperationTypes";
+import {
+ createNewStirlingFileStub,
+ createStirlingFile,
+ type StirlingFile,
+ type StirlingFileStub,
+} from "@app/types/fileContext";
+import { createTestStirlingFile } from "@app/tests/utils/testFileHelpers";
+import {
+ ToolFileEligibilityProvider,
+ useToolEligibleFileIds,
+} from "@app/contexts/ToolFileEligibilityContext";
+import { FileItem } from "@app/components/shared/FileSidebarFileItem";
+import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
+import { useCompressOperation } from "@app/hooks/tools/compress/useCompressOperation";
+import { defaultParameters as compressParameters } from "@app/hooks/tools/compress/useCompressParameters";
+
+const workspace = {
+ files: [] as StirlingFile[],
+ fileStubs: [] as StirlingFileStub[],
+};
+const viewer = { activeFileIndex: 0 };
+const navigation = { workbench: "fileEditor" };
+const selectors = {
+ getStirlingFileStub: (id: string) =>
+ workspace.fileStubs.find((stub) => stub.id === id),
+};
+const loadRecentFiles = vi.fn().mockResolvedValue([]);
+const onFileClick = vi.fn();
+const onPreviewRender = vi.fn();
+
+const pdfWorker = vi.hoisted(() => ({
+ createDocument: vi.fn(),
+ destroyDocument: vi.fn(),
+}));
+
+function FilePreviews() {
+ const eligibleFileIds = useToolEligibleFileIds();
+ onPreviewRender();
+ return workspace.files.map((file) => (
+ <FileItem
+ key={file.fileId}
+ fileId={file.fileId}
+ name={file.name}
+ isSelected
+ isActive={false}
+ isViewedInViewer={false}
+ isToolSkipped={
+ eligibleFileIds !== null && !eligibleFileIds.has(file.fileId)
+ }
+ onClick={onFileClick}
+ onEyeClick={vi.fn()}
+ />
+ ));
+}
+
+function EmptyFileSelectionTool({ filesVisible }: { filesVisible: boolean }) {
+ const operation = useCompressOperation();
+ return createToolFlow({
+ files: { selectedFiles: [], isVisible: filesVisible },
+ steps: [],
+ review: { isVisible: false, operation, title: "Results" },
+ });
+}
+
+vi.mock("@app/hooks/useLazyThumbnail", () => ({
+ useLazyThumbnail: () => undefined,
+}));
+
+vi.mock("@app/contexts/FileContext", () => ({
+ useAllFiles: () => ({
+ ...workspace,
+ fileIds: workspace.files.map((file) => file.fileId),
+ }),
+ useFileContext: () => ({ selectors, actions: {} }),
+ useFileSelectors: () => selectors,
+ useFileActions: () => ({ actions: {} }),
+ useFileSelection: () => ({ setSelectedFiles: vi.fn() }),
+ useFileManagement: () => ({ reorderFiles: vi.fn() }),
+}));
+vi.mock("@app/contexts/ViewerContext", () => ({
+ ViewerContext: createContext(null),
+ useViewer: () => viewer,
+}));
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigationState: () => navigation,
+ useNavigationActions: () => ({ actions: {} }),
+}));
+vi.mock("@app/contexts/PreferencesContext", () => ({
+ usePreferences: () => ({ preferences: {} }),
+}));
+vi.mock("@app/contexts/FilesModalContext", () => ({
+ useFilesModalContext: () => ({}),
+}));
+vi.mock("@app/hooks/useFileManager", () => ({
+ useFileManager: () => ({ loadRecentFiles }),
+}));
+vi.mock("@app/hooks/useEndpointConfig", () => ({
+ useEndpointEnabled: () => ({ enabled: true, loading: false }),
+}));
+vi.mock("@app/hooks/useBackendHealth", () => ({
+ useBackendHealth: () => ({ isOnline: true }),
+}));
+vi.mock("@app/services/pdfWorkerManager", () => ({
+ pdfWorkerManager: pdfWorker,
+}));
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: vi.fn() },
+ useTranslation: () => ({
+ t: (key: string, fallback?: string, options?: Record<string, unknown>) =>
+ (fallback ?? key).replace(/\{\{(\w+)\}\}/g, (_, name) =>
+ String(options?.[name]),
+ ),
+ }),
+}));
+vi.mock("@app/components/tools/compress/CompressSettings", () => ({
+ default: () => null,
+}));
+vi.mock(
+ "@app/components/tools/scannerImageSplit/ScannerImageSplitSettings",
+ () => ({
+ default: () => null,
+ }),
+);
+vi.mock("@app/components/tools/convert/ConvertSettings", () => ({
+ default: ({
+ parameters,
+ onParameterChange,
+ selectedFiles,
+ }: ToolAutomationSettingsProps<ConvertParameters> & {
+ selectedFiles: StirlingFile[];
+ }) => (
+ <>
+ <span data-testid="settings-file-count">{selectedFiles.length}</span>
+ {[
+ ["pdf", "png"],
+ ["pdf", "pdfua"],
+ ["image", "pdf"],
+ ["svg", "pdf"],
+ ].map(([from, to]) => (
+ <button
+ key={`${from}-${to}`}
+ onClick={() => {
+ onParameterChange("isSmartDetection", false);
+ onParameterChange("fromExtension", from);
+ onParameterChange("toExtension", to);
+ }}
+ >
+ {from} to {to}
+ </button>
+ ))}
+ {parameters.toExtension === "pdfua" && (
+ <ConvertToPdfUaSettings
+ parameters={parameters}
+ onParameterChange={onParameterChange}
+ selectedFiles={selectedFiles}
+ />
+ )}
+ </>
+ ),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ pdfWorker.createDocument.mockResolvedValue({ numPages: 0 });
+ viewer.activeFileIndex = 0;
+ navigation.workbench = "fileEditor";
+ workspace.files = [
+ createTestStirlingFile("report.pdf", "pdf", "application/pdf"),
+ createTestStirlingFile("photo.png", "png", "image/png"),
+ ];
+ workspace.fileStubs = workspace.files.map((file) =>
+ createNewStirlingFileStub(file, file.fileId),
+ );
+});
+
+describe("tool file selection", () => {
+ test("eligible selections keep their identity until file objects or order change", () => {
+ const secondPdf = createTestStirlingFile(
+ "second.pdf",
+ "pdf",
+ "application/pdf",
+ );
+ workspace.files.push(secondPdf);
+ workspace.fileStubs.push(
+ createNewStirlingFileStub(secondPdf, secondPdf.fileId),
+ );
+ const { result, rerender } = renderHook(useCompressOperation);
+ const first = result.current.getEligibleFiles?.(
+ compressParameters,
+ workspace.files,
+ );
+ expect(first).toEqual([workspace.files[0], secondPdf]);
+
+ rerender();
+ expect(
+ result.current.getEligibleFiles?.(
+ { ...compressParameters, compressionLevel: 7 },
+ [...workspace.files],
+ ),
+ ).toBe(first);
+
+ const reversed = result.current.getEligibleFiles?.(
+ compressParameters,
+ [...workspace.files].reverse(),
+ );
+ expect(reversed).toEqual([secondPdf, workspace.files[0]]);
+ expect(reversed).not.toBe(first);
+ });
+
+ test("typing Convert settings does not rerender previews or rescan an unchanged PDF", async () => {
+ const renderConvert = () => (
+ <MantineProvider>
+ <ToolFileEligibilityProvider>
+ <FilePreviews />
+ <Convert />
+ </ToolFileEligibilityProvider>
+ </MantineProvider>
+ );
+ const view = render(renderConvert());
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "pdf to pdfua" }));
+ await waitFor(() => expect(pdfWorker.destroyDocument).toHaveBeenCalled());
+ const previewRenders = onPreviewRender.mock.calls.length;
+
+ await user.type(
+ screen.getByRole("textbox", { name: "Document title" }),
+ "Updated title",
+ );
+ expect(pdfWorker.createDocument).toHaveBeenCalledTimes(1);
+ expect(onPreviewRender).toHaveBeenCalledTimes(previewRenders);
+
+ const original = workspace.files[0];
+ workspace.files = [
+ createStirlingFile(
+ new File(["updated pdf"], original.name, { type: original.type }),
+ original.fileId,
+ ),
+ workspace.files[1],
+ ];
+ view.rerender(renderConvert());
+ await waitFor(() =>
+ expect(pdfWorker.destroyDocument).toHaveBeenCalledTimes(2),
+ );
+ });
+
+ test("Merge requires two eligible PDFs and follows encryption changes", async () => {
+ const renderMerge = () => (
+ <MantineProvider>
+ <Merge />
+ </MantineProvider>
+ );
+ const view = render(renderMerge());
+ expect(
+ await screen.findByText(/Add at least 2 files to the workbench/),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Merge PDFs/ })).toBeDisabled();
+ expect(
+ screen.queryByRole("button", { name: "Sort" }),
+ ).not.toBeInTheDocument();
+
+ const secondPdf = createTestStirlingFile(
+ "second.pdf",
+ "pdf",
+ "application/pdf",
+ );
+ const secondStub = createNewStirlingFileStub(secondPdf, secondPdf.fileId);
+ workspace.files.push(secondPdf);
+ workspace.fileStubs.push(secondStub);
+ view.rerender(renderMerge());
+ expect(
+ await screen.findByText(/2 files$/, { selector: "p" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Merge PDFs/ })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Sort" })).toBeEnabled();
+
+ secondStub.processedFile = { pages: [], isEncrypted: true };
+ view.rerender(renderMerge());
+ expect(screen.getByRole("button", { name: /Merge PDFs/ })).toBeDisabled();
+ expect(
+ screen.queryByRole("button", { name: "Sort" }),
+ ).not.toBeInTheDocument();
+
+ secondStub.processedFile.isEncrypted = false;
+ view.rerender(renderMerge());
+ expect(screen.getByRole("button", { name: /Merge PDFs/ })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Sort" })).toBeEnabled();
+ });
+
+ test("hidden Files steps leave previews undimmed even with an empty selection", () => {
+ const renderFlow = (filesVisible: boolean) => (
+ <MantineProvider>
+ <ToolFileEligibilityProvider>
+ <FilePreviews />
+ <EmptyFileSelectionTool filesVisible={filesVisible} />
+ </ToolFileEligibilityProvider>
+ </MantineProvider>
+ );
+ const view = render(renderFlow(false));
+ const previews = [
+ screen.getByRole("button", { name: /report.pdf/ }),
+ screen.getByRole("button", { name: /photo.png/ }),
+ ];
+ for (const preview of previews) {
+ expect(preview).toHaveAttribute("data-tool-skipped", "false");
+ }
+
+ view.rerender(renderFlow(true));
+ for (const preview of previews) {
+ expect(preview).toHaveAttribute("data-tool-skipped", "true");
+ }
+
+ view.rerender(renderFlow(false));
+ for (const preview of previews) {
+ expect(preview).toHaveAttribute("data-tool-skipped", "false");
+ expect(preview).not.toHaveAttribute("aria-description");
+ }
+ });
+
+ test("previews dim with the current tool settings and recover when the tool closes", async () => {
+ const renderTool = (tool: ReactNode) => (
+ <MantineProvider>
+ <ToolFileEligibilityProvider>
+ <FilePreviews />
+ {tool}
+ </ToolFileEligibilityProvider>
+ </MantineProvider>
+ );
+ const view = render(renderTool(<Compress />));
+ const pdf = screen.getByRole("button", { name: /report.pdf/ });
+ const png = screen.getByRole("button", { name: /photo.png/ });
+ expect(pdf).toHaveAttribute("data-tool-skipped", "false");
+ expect(png).toHaveAttribute("data-tool-skipped", "true");
+ expect(png).toHaveAccessibleDescription("Not included in this tool run");
+ await userEvent.click(png);
+ expect(onFileClick).toHaveBeenCalledWith(workspace.files[1].fileId);
+
+ workspace.fileStubs[0].processedFile = { pages: [], isEncrypted: true };
+ view.rerender(renderTool(<Compress />));
+ expect(pdf).toHaveAttribute("data-tool-skipped", "true");
+ workspace.fileStubs[0].processedFile.isEncrypted = false;
+ view.rerender(renderTool(<Compress />));
+ expect(pdf).toHaveAttribute("data-tool-skipped", "false");
+
+ view.rerender(renderTool(<Convert />));
+ await userEvent.click(screen.getByRole("button", { name: "image to pdf" }));
+ expect(pdf).toHaveAttribute("data-tool-skipped", "true");
+ expect(png).toHaveAttribute("data-tool-skipped", "false");
+
+ await userEvent.click(screen.getByRole("button", { name: "svg to pdf" }));
+ expect(pdf).toHaveAttribute("data-tool-skipped", "true");
+ expect(png).toHaveAttribute("data-tool-skipped", "true");
+
+ view.rerender(renderTool(null));
+ expect(pdf).toHaveAttribute("data-tool-skipped", "false");
+ expect(png).toHaveAttribute("data-tool-skipped", "false");
+ expect(png).not.toHaveAttribute("aria-description");
+ });
+
+ test("Extract Image Scans selects an image and enables Run with no PDFs open", async () => {
+ workspace.files = workspace.files.slice(1);
+ workspace.fileStubs = workspace.fileStubs.slice(1);
+ render(
+ <MantineProvider>
+ <ScannerImageSplit />
+ </MantineProvider>,
+ );
+ expect(await screen.findByText("photo.png")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Extract Image Scans" }),
+ ).toBeEnabled();
+ });
+
+ test("Compress shows only eligible files and follows protection and viewer changes", async () => {
+ workspace.files.push(
+ createTestStirlingFile("empty.pdf", "", "application/pdf"),
+ );
+ const ui = (
+ <MantineProvider>
+ <Compress />
+ </MantineProvider>
+ );
+ const view = render(ui);
+ expect(await screen.findByText("report.pdf")).toBeInTheDocument();
+ expect(
+ screen.queryByText(/files$/, { selector: "p" }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Compress" })).toBeEnabled();
+
+ workspace.fileStubs[0].processedFile = { pages: [], isEncrypted: true };
+ view.rerender(
+ <MantineProvider>
+ <Compress />
+ </MantineProvider>,
+ );
+ expect(screen.queryByText("report.pdf")).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Compress" })).toBeDisabled();
+
+ workspace.fileStubs[0].processedFile.isEncrypted = false;
+ navigation.workbench = "viewer";
+ viewer.activeFileIndex = 1;
+ view.rerender(
+ <MantineProvider>
+ <Compress />
+ </MantineProvider>,
+ );
+ expect(screen.queryByText("report.pdf")).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Compress/ })).toBeDisabled();
+
+ viewer.activeFileIndex = 0;
+ view.rerender(
+ <MantineProvider>
+ <Compress />
+ </MantineProvider>,
+ );
+ expect(screen.getByText("report.pdf")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Compress/ })).toBeEnabled();
+ });
+
+ test("Convert updates Files, settings and Run count as parameters change", async () => {
+ workspace.files.push(
+ createTestStirlingFile("second.png", "png", "image/png"),
+ );
+ render(
+ <MantineProvider>
+ <Convert />
+ </MantineProvider>,
+ );
+ const user = userEvent.setup();
+
+ await user.click(screen.getByRole("button", { name: "pdf to png" }));
+ expect(await screen.findByText("report.pdf")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Convert Files" })).toBeEnabled();
+ expect(screen.getByTestId("settings-file-count")).toHaveTextContent("1");
+
+ await user.click(screen.getByRole("button", { name: "image to pdf" }));
+ expect(screen.getByText(/2 files$/, { selector: "p" })).toBeInTheDocument();
+ expect(screen.queryByText("report.pdf")).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Convert Files (2 files)" }),
+ ).toBeEnabled();
+ expect(screen.getByTestId("settings-file-count")).toHaveTextContent("2");
+
+ await user.click(screen.getByRole("button", { name: "svg to pdf" }));
+ expect(
+ screen.queryByText(/2 files$/, { selector: "p" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Convert Files" }),
+ ).toBeDisabled();
+ expect(screen.getByTestId("settings-file-count")).toHaveTextContent("0");
+
+ await user.click(screen.getByRole("button", { name: "pdf to png" }));
+ expect(screen.getByText("report.pdf")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Convert Files" })).toBeEnabled();
+ expect(screen.getByTestId("settings-file-count")).toHaveTextContent("1");
+ expect(workspace.files).toHaveLength(3);
+ });
+
+ test("PDF/UA offers image descriptions for one eligible PDF alongside a PNG", async () => {
+ render(
+ <MantineProvider>
+ <Convert />
+ </MantineProvider>,
+ );
+ await userEvent.click(screen.getByRole("button", { name: "pdf to pdfua" }));
+ expect(await screen.findByText("report.pdf")).toBeInTheDocument();
+ expect(screen.getByTestId("pdfua-find-figures")).toBeEnabled();
+ expect(
+ screen.queryByTestId("pdfua-alt-text-single-file-only"),
+ ).not.toBeInTheDocument();
+ expect(workspace.files).toHaveLength(2);
+ });
+});
diff --git a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
index eeea60976a..512259d5c5 100644
--- a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
+++ b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
@@ -21,8 +21,19 @@ import {
} from "vitest";
import { renderHook, act } from "@testing-library/react";
import { useConvertOperation } from "@app/hooks/tools/convert/useConvertOperation";
-import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
-import { FileContextProvider } from "@app/contexts/FileContext";
+import {
+ ConvertParameters,
+ defaultParameters,
+} from "@app/hooks/tools/convert/useConvertParameters";
+import { useRemovePasswordOperation } from "@app/hooks/tools/removePassword/useRemovePasswordOperation";
+import { useToolOperation } from "@app/hooks/tools/shared/useToolOperation";
+import { adjustContrastOperationConfig } from "@app/hooks/tools/adjustContrast/useAdjustContrastOperation";
+import { defaultParameters as contrastParameters } from "@app/hooks/tools/adjustContrast/useAdjustContrastParameters";
+import {
+ FileContextProvider,
+ useFileActions,
+ useFileState,
+} from "@app/contexts/FileContext";
import { NavigationProvider } from "@app/contexts/NavigationContext";
import { ToolRegistryProvider } from "@app/contexts/ToolRegistryProvider";
import { PreferencesProvider } from "@app/contexts/PreferencesContext";
@@ -31,7 +42,11 @@ import i18n from "@app/i18n/config";
import { createTestStirlingFile } from "@app/tests/utils/testFileHelpers";
import { expectConsole } from "@app/tests/failOnConsole";
import { fileStorage } from "@app/services/fileStorage";
-import { StirlingFile } from "@app/types/fileContext";
+import * as thumbnailUtils from "@app/utils/thumbnailUtils";
+import {
+ StirlingFile,
+ createNewStirlingFileStub,
+} from "@app/types/fileContext";
import { MantineProvider } from "@mantine/core";
// Mock axios (for static methods like CancelToken, isCancel)
@@ -64,7 +79,7 @@ vi.mock("../../services/apiClient", () => ({
// Import the mocked apiClient
import apiClient from "@app/services/apiClient";
-const mockedApiClient = vi.mocked(apiClient);
+const mockedApiClient = vi.mocked(apiClient, { deep: true });
// Mock only essential services that are actually called by the tests
vi.mock("../../services/fileStorage", () => ({
@@ -122,6 +137,201 @@ const TestWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
);
describe("Convert Tool Integration Tests", () => {
+ test("skips encrypted PDFs before invoking a custom processor without an endpoint", async () => {
+ const thumbnail = {
+ thumbnail: "data:image/png;base64,fake-thumbnail",
+ pageCount: 1,
+ };
+ vi.spyOn(thumbnailUtils, "generateThumbnailForFile").mockResolvedValue(
+ thumbnail.thumbnail,
+ );
+ vi.spyOn(
+ thumbnailUtils,
+ "generateThumbnailPairWithMetadata",
+ ).mockResolvedValue({
+ unrotated: thumbnail,
+ rotated: thumbnail,
+ });
+ const pdf = createPDFFile();
+ const locked = createTestStirlingFile(
+ "locked.pdf",
+ "encrypted",
+ "application/pdf",
+ );
+ const files = [locked, pdf];
+ const customProcessor = vi.fn().mockResolvedValue({ files: [pdf] });
+ const { result } = renderHook(
+ () => ({
+ operation: useToolOperation({
+ ...adjustContrastOperationConfig,
+ customProcessor,
+ }),
+ context: useFileActions(),
+ ...useFileState(),
+ }),
+ { wrapper: TestWrapper },
+ );
+ await act(async () => {
+ result.current.context.dispatch({
+ type: "ADD_FILES",
+ payload: {
+ stirlingFileStubs: files.map((file) => ({
+ ...createNewStirlingFileStub(file, file.fileId),
+ processedFile:
+ file === locked ? { pages: [], isEncrypted: true } : undefined,
+ })),
+ },
+ });
+ });
+ expect(
+ result.current.operation.getEligibleFiles?.(contrastParameters, files),
+ ).toEqual([pdf]);
+
+ await act(async () => {
+ await result.current.operation.executeOperation(
+ contrastParameters,
+ files,
+ );
+ });
+ expect(customProcessor).toHaveBeenCalledExactlyOnceWith(
+ contrastParameters,
+ [pdf],
+ );
+ expect(result.current.operation.errorMessage).toBe(null);
+ expect(result.current.state.files.byId[locked.fileId].isLeaf).toBe(true);
+ expect(result.current.state.ui.errorFileIds).not.toContain(locked.fileId);
+ expect(fileStorage.persistVersionedOutputs).toHaveBeenLastCalledWith(
+ [pdf.fileId],
+ expect.any(Array),
+ expect.any(Array),
+ );
+
+ await act(async () => {
+ await result.current.operation.executeOperation(contrastParameters, [
+ locked,
+ ]);
+ });
+ expect(customProcessor).toHaveBeenCalledTimes(1);
+ expect(result.current.operation.errorMessage).toBe("noValidFiles");
+ });
+
+ test("filters mixed inputs using current params and protection without consuming skipped files", async () => {
+ mockedApiClient.post.mockResolvedValue({
+ data: new Blob(["output"]),
+ headers: {},
+ });
+ const { result } = renderHook(
+ () => ({
+ convert: useConvertOperation(),
+ unlock: useRemovePasswordOperation(),
+ context: useFileActions(),
+ ...useFileState(),
+ }),
+ { wrapper: TestWrapper },
+ );
+ const pdf = createPDFFile();
+ const svg = createTestStirlingFile(
+ "drawing.svg",
+ "<svg/>",
+ "image/svg+xml",
+ );
+ const image = createTestStirlingFile("photo.png", "image", "image/png");
+ const locked = createTestStirlingFile(
+ "locked.pdf",
+ "encrypted",
+ "application/pdf",
+ );
+ const files = [image, locked, pdf, svg];
+ await act(async () => {
+ result.current.context.dispatch({
+ type: "ADD_FILES",
+ payload: {
+ stirlingFileStubs: files.map((file) => ({
+ ...createNewStirlingFileStub(file, file.fileId),
+ versionNumber: 2,
+ processedFile:
+ file === locked ? { pages: [], isEncrypted: true } : undefined,
+ })),
+ },
+ });
+ });
+
+ await act(async () => {
+ await result.current.convert.executeOperation(
+ { ...defaultParameters, fromExtension: "pdf", toExtension: "png" },
+ files,
+ );
+ });
+ expect(mockedApiClient.post).toHaveBeenCalledTimes(1);
+ expect(mockedApiClient.post.mock.calls[0][0]).toBe(
+ "/api/v1/convert/pdf/img",
+ );
+ expect(
+ (mockedApiClient.post.mock.calls[0][1] as FormData).getAll("fileInput"),
+ ).toEqual([pdf]);
+ expect(fileStorage.persistVersionedOutputs).toHaveBeenLastCalledWith(
+ [pdf.fileId],
+ expect.any(Array),
+ expect.any(Array),
+ );
+ for (const file of [image, svg, locked]) {
+ expect(result.current.state.files.byId[file.fileId].isLeaf).toBe(true);
+ expect(result.current.state.ui.errorFileIds).not.toContain(file.fileId);
+ }
+
+ await act(async () => {
+ await result.current.convert.executeOperation(
+ { ...defaultParameters, fromExtension: "svg", toExtension: "pdf" },
+ files,
+ );
+ });
+ expect(mockedApiClient.post).toHaveBeenCalledTimes(2);
+ expect(mockedApiClient.post.mock.calls[1][0]).toBe(
+ "/api/v1/convert/svg/pdf",
+ );
+ expect(
+ (mockedApiClient.post.mock.calls[1][1] as FormData).getAll("fileInput"),
+ ).toEqual([svg]);
+ expect(fileStorage.persistVersionedOutputs).toHaveBeenLastCalledWith(
+ [svg.fileId],
+ expect.any(Array),
+ expect.any(Array),
+ );
+
+ await act(async () => {
+ await result.current.convert.executeOperation(
+ { ...defaultParameters, fromExtension: "pdf", toExtension: "png" },
+ [image, locked],
+ );
+ });
+ expect(mockedApiClient.post).toHaveBeenCalledTimes(2);
+ expect(fileStorage.persistVersionedOutputs).toHaveBeenCalledTimes(2);
+ expect(result.current.convert.errorMessage).toBe("noValidFiles");
+
+ await act(async () => {
+ await result.current.unlock.executeOperation({ password: "secret" }, [
+ image,
+ locked,
+ ]);
+ });
+ expect(mockedApiClient.post).toHaveBeenCalledTimes(3);
+ expect(mockedApiClient.post.mock.calls[2][0]).toBe(
+ "/api/v1/security/remove-password",
+ );
+ expect(
+ (mockedApiClient.post.mock.calls[2][1] as FormData).get("password"),
+ ).toBe("secret");
+ expect(
+ (mockedApiClient.post.mock.calls[2][1] as FormData).getAll("fileInput"),
+ ).toEqual([locked]);
+ expect(result.current.unlock.errorMessage).toBe(null);
+ expect(fileStorage.persistVersionedOutputs).toHaveBeenLastCalledWith(
+ [locked.fileId],
+ expect.any(Array),
+ expect.any(Array),
+ );
+ });
+
beforeEach(() => {
vi.clearAllMocks();
// Setup default apiClient mock
@@ -244,9 +454,9 @@ describe("Convert Tool Integration Tests", () => {
});
const testFile = createTestStirlingFile(
- "invalid.txt",
+ "invalid.pdf",
"not a pdf",
- "text/plain",
+ "application/pdf",
);
const parameters: ConvertParameters = {
fromExtension: "pdf",
diff --git a/frontend/editor/src/core/tests/stubbed/merge-response-handling.spec.ts b/frontend/editor/src/core/tests/stubbed/merge-response-handling.spec.ts
index 20a96e32f4..7443b2155a 100644
--- a/frontend/editor/src/core/tests/stubbed/merge-response-handling.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/merge-response-handling.spec.ts
@@ -15,6 +15,7 @@ import fs from "fs";
const FIXTURES_DIR = path.join(import.meta.dirname, "../test-fixtures");
const SAMPLE_PDF = path.join(FIXTURES_DIR, "sample.pdf");
+const MULTI_PAGE_PDF = path.join(FIXTURES_DIR, "multi-page-sample.pdf");
const SAMPLE_PDF_BYTES = fs.readFileSync(SAMPLE_PDF);
async function mockMergeWithContentType(page: Page, contentType: string) {
@@ -32,7 +33,7 @@ async function mockMergeWithContentType(page: Page, contentType: string) {
async function runMergeAndOpenReview(page: Page) {
await page.goto("/merge");
- await uploadFiles(page, [SAMPLE_PDF, SAMPLE_PDF]);
+ await uploadFiles(page, [SAMPLE_PDF, MULTI_PAGE_PDF]);
await switchToEditorIfViewerMode(page);
await runToolAndWaitForReview(page);
}
diff --git a/frontend/editor/src/core/tools/AddAttachments.tsx b/frontend/editor/src/core/tools/AddAttachments.tsx
index 17e5d7b0b1..16f449568a 100644
--- a/frontend/editor/src/core/tools/AddAttachments.tsx
+++ b/frontend/editor/src/core/tools/AddAttachments.tsx
@@ -97,7 +97,9 @@ const AddAttachments = ({
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles:
+ operation.getEligibleFiles?.(params.parameters, selectedFiles) ??
+ selectedFiles,
isCollapsed: hasResults,
},
steps: getSteps(),
diff --git a/frontend/editor/src/core/tools/AddPageNumbers.tsx b/frontend/editor/src/core/tools/AddPageNumbers.tsx
index 7001dc2894..1853d05961 100644
--- a/frontend/editor/src/core/tools/AddPageNumbers.tsx
+++ b/frontend/editor/src/core/tools/AddPageNumbers.tsx
@@ -113,7 +113,9 @@ const AddPageNumbers = ({
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles:
+ operation.getEligibleFiles?.(params.parameters, selectedFiles) ??
+ selectedFiles,
isCollapsed: hasResults,
},
steps: getSteps(),
diff --git a/frontend/editor/src/core/tools/AddPassword.tsx b/frontend/editor/src/core/tools/AddPassword.tsx
index 615ab52b9a..453eec0ab9 100644
--- a/frontend/editor/src/core/tools/AddPassword.tsx
+++ b/frontend/editor/src/core/tools/AddPassword.tsx
@@ -78,7 +78,11 @@ const AddPassword = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles:
+ addPasswordOperation.getEligibleFiles?.(
+ addPasswordParams.fullParameters,
+ selectedFiles,
+ ) ?? selectedFiles,
isCollapsed: hasResults,
},
steps: [
diff --git a/frontend/editor/src/core/tools/AddStamp.tsx b/frontend/editor/src/core/tools/AddStamp.tsx
index 6070ae5e89..b85455ffb9 100644
--- a/frontend/editor/src/core/tools/AddStamp.tsx
+++ b/frontend/editor/src/core/tools/AddStamp.tsx
@@ -197,7 +197,9 @@ const AddStamp = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles:
+ operation.getEligibleFiles?.(params.parameters, selectedFiles) ??
+ selectedFiles,
isCollapsed: hasResults,
},
steps: getSteps(),
diff --git a/frontend/editor/src/core/tools/AddWatermark.tsx b/frontend/editor/src/core/tools/AddWatermark.tsx
index 75652e9d82..e42027818c 100644
--- a/frontend/editor/src/core/tools/AddWatermark.tsx
+++ b/frontend/editor/src/core/tools/AddWatermark.tsx
@@ -213,7 +213,11 @@ const AddWatermark = ({
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles:
+ watermarkOperation.getEligibleFiles?.(
+ watermarkParams.parameters,
+ selectedFiles,
+ ) ?? selectedFiles,
isCollapsed: hasResults,
},
steps: getSteps(),
diff --git a/frontend/editor/src/core/tools/Convert.tsx b/frontend/editor/src/core/tools/Convert.tsx
index 733a21b6e4..e60723be6b 100644
--- a/frontend/editor/src/core/tools/Convert.tsx
+++ b/frontend/editor/src/core/tools/Convert.tsx
@@ -138,9 +138,15 @@ const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
onPreviewFile?.(null);
};
+ const eligibleFiles =
+ convertOperation.getEligibleFiles?.(
+ convertParams.parameters,
+ selectedFiles,
+ ) ?? selectedFiles;
+
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles: eligibleFiles,
isCollapsed: hasResults,
},
steps: [
@@ -153,7 +159,7 @@ const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
parameters={convertParams.parameters}
onParameterChange={convertParams.updateParameter}
getAvailableToExtensions={convertParams.getAvailableToExtensions}
- selectedFiles={selectedFiles}
+ selectedFiles={eligibleFiles}
onSourceFormatSelected={handleSourceFormatSelected}
disabled={endpointLoading}
/>
diff --git a/frontend/editor/src/core/tools/OCR.tsx b/frontend/editor/src/core/tools/OCR.tsx
index 94477c053d..257d1c26c7 100644
--- a/frontend/editor/src/core/tools/OCR.tsx
+++ b/frontend/editor/src/core/tools/OCR.tsx
@@ -88,7 +88,9 @@ const OCR = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles:
+ ocrOperation.getEligibleFiles?.(ocrParams.parameters, selectedFiles) ??
+ selectedFiles,
isCollapsed: hasResults,
},
steps: [
diff --git a/frontend/editor/src/core/tools/ReorganizePages.tsx b/frontend/editor/src/core/tools/ReorganizePages.tsx
index 024469bee4..9823c4faf9 100644
--- a/frontend/editor/src/core/tools/ReorganizePages.tsx
+++ b/frontend/editor/src/core/tools/ReorganizePages.tsx
@@ -82,7 +82,9 @@ const ReorganizePages = ({
return createToolFlow({
files: {
- selectedFiles,
+ selectedFiles:
+ operation.getEligibleFiles?.(params.parameters, selectedFiles) ??
+ selectedFiles,
isCollapsed: hasResults,
},
steps,
diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.ts
index 9d672b2d6d..f67349917c 100644
--- a/frontend/editor/src/core/types/toolIO.ts
+++ b/frontend/editor/src/core/types/toolIO.ts
@@ -65,6 +65,47 @@ export const TOOL_FORMATS = [
"NONE",
] as const satisfies readonly ToolFormat[];
+/** Filename extensions from the backend ToolFormat declarations. */
+export const TOOL_FORMAT_EXTENSIONS: Record<ToolFormat, readonly string[]> = {
+ PDF: ["pdf"],
+ PDF_ENCRYPTED: ["pdf"],
+ IMAGE: [
+ "png",
+ "jpg",
+ "jpeg",
+ "gif",
+ "webp",
+ "bmp",
+ "tif",
+ "tiff",
+ "svg",
+ "psd",
+ "ai",
+ "eps",
+ ],
+ ZIP: ["zip", "rar", "7z", "tar", "gz", "bz2", "xz", "lz", "lzma", "z"],
+ WORD: ["doc", "docx", "odt", "rtf"],
+ PPT: ["ppt", "pptx", "odp"],
+ EXCEL: ["xls", "xlsx", "ods"],
+ CSV: ["csv"],
+ HTML: ["html", "htm", "xhtml"],
+ XML: ["xml", "xsd", "xsl"],
+ JSON: ["json"],
+ TEXT: ["txt", "text", "md", "markdown"],
+ MARKDOWN: ["md", "markdown"],
+ JAVASCRIPT: ["js", "jsx"],
+ EBOOK: ["epub", "mobi", "azw3", "fb2", "txt", "docx"],
+ EMAIL: ["eml", "msg"],
+ POSTSCRIPT: ["ps", "eps"],
+ PCL: ["pcl", "pxl"],
+ XPS: ["xps", "oxps"],
+ VIDEO: ["mp4", "webm", "avi", "mov", "mkv"],
+ CBZ: ["cbz"],
+ CBR: ["cbr"],
+ ANY: [],
+ NONE: [],
+};
+
/** How many files go in and come out. A multi-output tool returns its results zipped, and the caller unpacks them. */
export type ToolArity = "SISO" | "SIMO" | "MISO" | "MIMO";
@@ -86,6 +127,8 @@ export interface ToolIOCase {
/** What one endpoint accepts and produces. */
export interface ToolIOSpec {
accepts: ToolFormat[];
+ /** Overrides the broad format categories for filename-based input checks. */
+ inputExtensions?: string[];
produces: ToolFormat;
arity: ToolArity;
cases?: ToolIOCase[];
@@ -108,11 +151,13 @@ export const TOOL_IO: ToolIOTable = {
accepts: ["CBR"],
produces: "PDF",
arity: "SISO",
+ inputExtensions: ["cbr", "rar"],
},
"/api/v1/convert/cbz/pdf": {
accepts: ["CBZ"],
produces: "PDF",
arity: "SISO",
+ inputExtensions: ["cbz", "zip"],
},
"/api/v1/convert/ebook/pdf": {
accepts: ["EBOOK"],
@@ -133,16 +178,48 @@ export const TOOL_IO: ToolIOTable = {
accepts: ["HTML", "ZIP"],
produces: "PDF",
arity: "SISO",
+ inputExtensions: ["html", "zip"],
},
"/api/v1/convert/img/pdf": {
accepts: ["IMAGE"],
produces: "PDF",
arity: "MISO",
+ inputExtensions: [
+ "bmp",
+ "btf",
+ "btiff",
+ "cur",
+ "emf",
+ "gif",
+ "ico",
+ "jb2",
+ "jbig2",
+ "jp2",
+ "jpeg",
+ "jpg",
+ "pbm",
+ "pcx",
+ "pgm",
+ "png",
+ "ppm",
+ "psb",
+ "psd",
+ "rle",
+ "svg",
+ "tf8",
+ "tif",
+ "tiff",
+ "wbmp",
+ "wbp",
+ "webp",
+ "wmf",
+ ],
},
"/api/v1/convert/markdown/pdf": {
accepts: ["MARKDOWN", "ZIP"],
produces: "PDF",
arity: "SISO",
+ inputExtensions: ["md", "zip"],
},
"/api/v1/convert/pdf/cbr": {
accepts: ["PDF"],
@@ -260,6 +337,7 @@ export const TOOL_IO: ToolIOTable = {
accepts: ["IMAGE"],
produces: "PDF",
arity: "MIMO",
+ inputExtensions: ["svg"],
cases: [
{
when: [
@@ -488,9 +566,34 @@ export const TOOL_IO: ToolIOTable = {
arity: "SISO",
},
"/api/v1/misc/extract-image-scans": {
- accepts: ["PDF"],
+ accepts: ["PDF", "IMAGE"],
produces: "IMAGE",
arity: "SIMO",
+ inputExtensions: [
+ "pdf",
+ "bmp",
+ "dib",
+ "gif",
+ "jpeg",
+ "jpg",
+ "jpe",
+ "jp2",
+ "png",
+ "webp",
+ "avif",
+ "pbm",
+ "pgm",
+ "ppm",
+ "pxm",
+ "pnm",
+ "pfm",
+ "sr",
+ "ras",
+ "tiff",
+ "tif",
+ "hdr",
+ "pic",
+ ],
},
"/api/v1/misc/extract-images": {
accepts: ["PDF"],
diff --git a/frontend/editor/src/core/utils/fileUtils.test.ts b/frontend/editor/src/core/utils/fileUtils.test.ts
index fcdb539264..0c6ed6557b 100644
--- a/frontend/editor/src/core/utils/fileUtils.test.ts
+++ b/frontend/editor/src/core/utils/fileUtils.test.ts
@@ -4,9 +4,28 @@ import {
detectFileExtension,
formatFileSize,
detectNonPdfFileType,
+ getFileFormats,
} from "@app/utils/fileUtils";
describe("fileUtils", () => {
+ it("classifies using existing PDF detection, stored protection and overlapping backend categories", () => {
+ expect(
+ getFileFormats({ name: "download", type: "application/pdf" }),
+ ).toEqual(["PDF"]);
+ expect(getFileFormats({ name: "document.PDF", type: "" })).toEqual(["PDF"]);
+ expect(getFileFormats({ name: "document.docx", type: "" })).toEqual([
+ "WORD",
+ "EBOOK",
+ ]);
+ expect(getFileFormats({ name: "unknown", type: "" })).toEqual([]);
+ expect(
+ getFileFormats({
+ name: "document.pdf",
+ type: "",
+ processedFile: { pages: [], isEncrypted: true },
+ }),
+ ).toEqual(["PDF_ENCRYPTED"]);
+ });
describe("isPdfFile", () => {
it("should return true for PDF files with correct MIME type", () => {
const pdfFile = new File(["content"], "document.pdf", {
diff --git a/frontend/editor/src/core/utils/fileUtils.ts b/frontend/editor/src/core/utils/fileUtils.ts
index 13002db52e..e71f69e86d 100644
--- a/frontend/editor/src/core/utils/fileUtils.ts
+++ b/frontend/editor/src/core/utils/fileUtils.ts
@@ -1,4 +1,9 @@
-// Pure utility functions for file operations
+import {
+ TOOL_FORMATS,
+ TOOL_FORMAT_EXTENSIONS,
+ type ToolFormat,
+} from "@app/types/toolIO";
+import type { StirlingFileStub } from "@app/types/fileContext";
/**
* Consolidated file size formatting utility
@@ -109,6 +114,21 @@ export function isPdfFile(
return false;
}
+/**
+ * Uses FileContext's detected password protection when present; no file bytes are read.
+ * Multiple categories can match (for example DOCX is both WORD and EBOOK); unknown files match none.
+ */
+export function getFileFormats(
+ file: Pick<StirlingFileStub, "name" | "type" | "processedFile">,
+): ToolFormat[] {
+ if (file.processedFile?.isEncrypted) return ["PDF_ENCRYPTED"];
+ if (isPdfFile(file)) return ["PDF"];
+ const extension = detectFileExtension(file.name);
+ return TOOL_FORMATS.filter((format) =>
+ TOOL_FORMAT_EXTENSIONS[format].includes(extension),
+ );
+}
+
export type NonPdfFileType =
| "image"
| "csv"
diff --git a/frontend/editor/src/core/utils/toolIOCompat.test.ts b/frontend/editor/src/core/utils/toolIOCompat.test.ts
index b3fb117705..23dbf1d92a 100644
--- a/frontend/editor/src/core/utils/toolIOCompat.test.ts
+++ b/frontend/editor/src/core/utils/toolIOCompat.test.ts
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import {
validateToolChain,
+ toolAcceptsFile,
type ToolChainStep,
type ToolDiagnostic,
} from "@app/utils/toolIOCompat";
@@ -75,3 +76,65 @@ describe("tool chain conformance", () => {
});
}
});
+
+describe("tool file inputs", () => {
+ it.each([
+ ["/api/v1/misc/compress-pdf", "document.PDF", true],
+ ["/api/v1/misc/compress-pdf", "photo.png", false],
+ ["/api/v1/misc/extract-image-scans", "document.PDF", true],
+ ["/api/v1/misc/extract-image-scans", "scan.png", true],
+ ["/api/v1/misc/extract-image-scans", "scan.JPEG", true],
+ ["/api/v1/misc/extract-image-scans", "scan.tiff", true],
+ ["/api/v1/misc/extract-image-scans", "scan.pgm", true],
+ ["/api/v1/misc/extract-image-scans", "drawing.svg", false],
+ ["/api/v1/misc/extract-image-scans", "drawing.psd", false],
+ ["/api/v1/misc/extract-image-scans", "document.docx", false],
+ ["/api/v1/convert/svg/pdf", "drawing.svg", true],
+ ["/api/v1/convert/svg/pdf", "photo.png", false],
+ ["/api/v1/convert/html/pdf", "site.zip", true],
+ ["/api/v1/convert/html/pdf", "site.rar", false],
+ ["/api/v1/convert/markdown/pdf", "readme.txt", false],
+ ["/api/v1/convert/markdown/pdf", "site.zip", true],
+ ["/api/v1/convert/img/pdf", "photo.jpeg", true],
+ ["/api/v1/convert/img/pdf", "photo.wbmp", true],
+ ["/api/v1/convert/img/pdf", "drawing.eps", false],
+ ["/api/v1/convert/cbz/pdf", "book.zip", true],
+ ["/api/v1/convert/cbr/pdf", "book.rar", true],
+ ["/api/v1/convert/ebook/pdf", "document.docx", true],
+ ["/api/v1/misc/compress-pdf", "unknown", false],
+ ])("checks %s against %s", (endpoint, name, accepted) => {
+ expect(toolAcceptsFile(endpoint, { name, type: "" })).toBe(accepted);
+ });
+
+ it("uses detected protection and the endpoint's encrypted input declaration", () => {
+ const file = {
+ name: "document.pdf",
+ type: "",
+ processedFile: { pages: [], isEncrypted: true },
+ };
+ expect(toolAcceptsFile("/api/v1/misc/compress-pdf", file)).toBe(false);
+ expect(toolAcceptsFile("/api/v1/misc/extract-image-scans", file)).toBe(
+ false,
+ );
+ expect(toolAcceptsFile("/api/v1/security/remove-password", file)).toBe(
+ true,
+ );
+ expect(toolAcceptsFile("/api/v1/convert/file/pdf", file)).toBe(true);
+ file.processedFile.isEncrypted = false;
+ expect(toolAcceptsFile("/api/v1/misc/compress-pdf", file)).toBe(true);
+ });
+
+ it.each([undefined, "/unknown"])(
+ "skips encrypted PDFs without a declaration for %s",
+ (endpoint) => {
+ const file = {
+ name: "document.pdf",
+ type: "application/pdf",
+ processedFile: { pages: [], isEncrypted: true },
+ };
+ expect(toolAcceptsFile(endpoint, file)).toBe(false);
+ file.processedFile.isEncrypted = false;
+ expect(toolAcceptsFile(endpoint, file)).toBe(true);
+ },
+ );
+});
diff --git a/frontend/editor/src/core/utils/toolIOCompat.ts b/frontend/editor/src/core/utils/toolIOCompat.ts
index 473195ff7b..4753bf958a 100644
--- a/frontend/editor/src/core/utils/toolIOCompat.ts
+++ b/frontend/editor/src/core/utils/toolIOCompat.ts
@@ -14,6 +14,8 @@ import {
type ToolIOSpec,
type ToolIOTable,
} from "@app/types/toolIO";
+import { detectFileExtension, getFileFormats } from "@app/utils/fileUtils";
+import type { StirlingFileStub } from "@app/types/fileContext";
export type ToolDiagnosticSeverity = "ERROR" | "WARN" | "INFO";
@@ -259,6 +261,27 @@ export function toolAcceptsFormat(
return spec ? acceptsFormat(spec, format) : true;
}
+/**
+ * Uses detected encryption and endpoint input restrictions. Encrypted PDFs require declared support;
+ * undeclared endpoints keep their own validation for other inputs.
+ */
+export function toolAcceptsFile(
+ operation: string | undefined,
+ file: Pick<StirlingFileStub, "name" | "type" | "processedFile">,
+): boolean {
+ const spec = operation ? toolIOFor(operation) : undefined;
+ const formats = getFileFormats(file);
+ if (
+ formats.includes("PDF_ENCRYPTED") &&
+ (!spec || !acceptsFormat(spec, "PDF_ENCRYPTED"))
+ )
+ return false;
+ if (!spec || spec.accepts.includes("ANY")) return true;
+ if (spec.inputExtensions)
+ return spec.inputExtensions.includes(detectFileExtension(file.name));
+ return formats.some((format) => acceptsFormat(spec, format));
+}
+
export function hasBlockingDiagnostics(diagnostics: ToolDiagnostic[]): boolean {
return diagnostics.some((d) => d.severity === "ERROR");
}