#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Support using Convert in Pipelines (#7290)
James Brunton998e8511301a
diff --git a/frontend/.storybook/a11y-baseline.json b/frontend/.storybook/a11y-baseline.jsonindex c3fcfad6ea..0245e3101a 100644--- a/frontend/.storybook/a11y-baseline.json+++ b/frontend/.storybook/a11y-baseline.json@@ -2013,6 +2013,9 @@"editor/src/portal/components/pipelines/PipelinesTable.stories.tsx :: Empty": ["empty-table-header"],+ "editor/src/portal/components/pipelines/ToolPicker.stories.tsx :: Default": [+ "color-contrast"+ ],"editor/src/portal/components/policies/PolicyCategoryCard.stories.tsx :: Coming Soon": ["color-contrast"],diff --git a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsxindex fe4a6f8e48..c3ee0758f6 100644--- a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx+++ b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx@@ -10,9 +10,6 @@ import {getAvailableToExtensions as defaultGetAvailableToExtensions,} from "@app/utils/convertUtils";import { getConversionEndpoints } from "@app/data/toolsTaxonomy";-import { useFileSelection } from "@app/contexts/FileContext";-import { useFileSelector, useFileSelectors } from "@app/contexts/FileContext";-import { detectFileExtension } from "@app/utils/fileUtils";import { usePreferences } from "@app/contexts/PreferencesContext";import { useConversionCloudStatus } from "@app/hooks/useConversionCloudStatus";import GroupedFormatDropdown from "@app/components/tools/convert/GroupedFormatDropdown";@@ -49,6 +46,12 @@ interface ConvertSettingsProps {fromExtension: string,) => Array<{ value: string; label: string; group: string }>;selectedFiles?: StirlingFile[];+ /**+ * Called with the newly chosen source format. The editor uses this to select the loaded files+ * that match; surfaces without loaded files (automation, pipeline builder) simply omit it. Keeping+ * the file-selection side effect out of here is what lets this component render outside FileContext.+ */+ onSourceFormatSelected?: (fromExtension: string) => void;disabled?: boolean;}@@ -57,13 +60,11 @@ const ConvertSettings = ({onParameterChange,getAvailableToExtensions = defaultGetAvailableToExtensions,selectedFiles = [],+ onSourceFormatSelected,disabled = false,}: ConvertSettingsProps) => {const { t } = useTranslation();const theme = useMantineTheme();- const { setSelectedFiles } = useFileSelection();- const selectors = useFileSelectors();- const activeFiles = useFileSelector((s) => s.files.ids);const { preferences } = usePreferences();const allEndpoints = useMemo(() => {@@ -234,39 +235,12 @@ const ConvertSettings = ({onParameterChange("toExtension", autoTarget);};- const filterFilesByExtension = (extension: string) => {- const files = activeFiles- .map((fileId) => selectors.getFile(fileId))- .filter(Boolean) as StirlingFile[];- return files.filter((file) => {- const fileExtension = detectFileExtension(file.name);-- if (extension === "any") {- return true;- } else if (extension === "image") {- return isImageFormat(fileExtension);- } else {- return fileExtension === extension;- }- });- };-- const updateFileSelection = (files: StirlingFile[]) => {- const fileIds = files.map((file) => file.fileId);- setSelectedFiles(fileIds);- };-const handleFromExtensionChange = (value: string) => {onParameterChange("fromExtension", value);setAutoTargetExtension(value);resetParametersToDefaults();-- if (activeFiles.length > 0) {- const matchingFiles = filterFilesByExtension(value);- updateFileSelection(matchingFiles);- } else {- updateFileSelection([]);- }+ // Editor-only: let the host select the loaded files matching this source format.+ onSourceFormatSelected?.(value);};const handleToExtensionChange = (value: string) => {diff --git a/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.ts b/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.tsindex d329f1feb0..19335373f1 100644--- a/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.ts+++ b/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.ts@@ -19,6 +19,17 @@ import {isWebFormat,isOfficeFormat,} from "@app/utils/convertUtils";+import {+ isToolEndpoint,+ type ToolApiParams,+ type ToolEndpoint,+} from "@app/hooks/tools/shared/toolApiMapping";+import {+ CONVERSION_ENDPOINTS,+ COLOR_TYPES,+ OUTPUT_OPTIONS,+ FIT_OPTIONS,+} from "@app/constants/convertConstants";import { useToolCloudStatus } from "@app/hooks/useToolCloudStatus";// Static function that can be used by both the hook and automation executor@@ -300,18 +311,262 @@ export const convertProcessor = async (};};+// Every backend endpoint the Convert tool may resolve to. Declaring the full set lets a stored+// convert step map back to this tool by endpoint membership (its from/to selectors are+// frontend-only, recovered from the step's bookkeeping params on deserialize).+export const CONVERT_AUTOMATION_ENDPOINTS: readonly ToolEndpoint[] = Array.from(+ new Set(Object.values(CONVERSION_ENDPOINTS)),+).filter(isToolEndpoint);++/**+ * The backend endpoint a conversion targets (PDF/X shares the PDF/A endpoint). Undefined until both+ * formats are chosen, or when the pair maps to no known endpoint. The single place the from/to ->+ * endpoint mapping lives, shared by the tool config's `endpoint` and the deserialize reader below.+ */+export const convertEndpointFor = (+ fromExtension: string,+ toExtension: string,+): ToolEndpoint | undefined => {+ if (!fromExtension || !toExtension) return undefined;+ const actualTo = toExtension === "pdfx" ? "pdfa" : toExtension;+ const url = getEndpointUrl(fromExtension, actualTo);+ return url && isToolEndpoint(url) ? url : undefined;+};++/**+ * A convert step spans many backend endpoints, each with its own request model, so its body can't+ * be typed as a single generated model. It is built from the same buildConvertFormData the client+ * runner uses - the one source of truth for each conversion's fields - and cast at this boundary.+ * `fromExtension`/`toExtension` ride along as bookkeeping: the endpoints ignore them (they are+ * encoded in the path), but the chosen conversion can't be reconstructed from the body alone, so+ * they let deserialize recover it. See toolAutomation.serializeToolStep.+ */+export const convertToApiParams = (+ params: ConvertParameters,+): ToolApiParams[ToolEndpoint] => {+ const dummy = new File([], "input", { type: "application/octet-stream" });+ const formData = buildConvertFormData(params, [dummy]);+ const body: Record<string, string> = {+ fromExtension: params.fromExtension,+ toExtension: params.toExtension,+ };+ // Keep the scalar fields; the file part (fileInput) is fed separately by the engine.+ formData.forEach((value, key) => {+ if (typeof value === "string") body[key] = value;+ });+ return body as unknown as ToolApiParams[ToolEndpoint];+};++/**+ * The fields a convert endpoint accepts - taken from its generated request model - but valued as the+ * strings a stored, form-shaped step actually holds. Keying off the model's `keyof` means a reader+ * can only read a field that endpoint really takes (a typo is a compile error). Values stay strings+ * because that is what a serialized step carries; and two of these models spell their enum *values*+ * for the backend rather than for the tool (colorType, fitOption), so values are validated against+ * the frontend's own sets (asEnum) rather than the model's.+ */+type ConvertStepBody<E extends ToolEndpoint> = Partial<+ Record<keyof ToolApiParams[E], string>+>;++/** Per-endpoint readers: each is handed exactly its endpoint's fields. */+type ConvertOptionReaders = {+ [E in ToolEndpoint]?: (+ body: ConvertStepBody<E>,+ toExtension: string,+ ) => Partial<ConvertParameters>;+};++/** The reader shape collapsed for the runtime dispatch, where the endpoint is only a string. */+type ConvertOptionReader = (+ body: Record<string, string | undefined>,+ toExtension: string,+) => Partial<ConvertParameters>;++// The stored values are strings; these read one back into the typed shape ConvertParameters expects,+// validating an enum against its allowed set (asEnum) rather than blind-casting an arbitrary string.+const asFlag = (value: string | undefined): boolean => value === "true";+const asInt = (value: string | undefined, fallback: number): number =>+ value !== undefined && value !== "" ? Number(value) : fallback;+const asEnum = <T extends string>(+ value: string | undefined,+ allowed: readonly T[],+ fallback: T,+): T => (allowed.includes(value as T) ? (value as T) : fallback);++const COLOR_TYPE_VALUES = [+ COLOR_TYPES.COLOR,+ COLOR_TYPES.GRAYSCALE,+ COLOR_TYPES.BLACK_WHITE,+] as const;+const OUTPUT_OPTION_VALUES = [+ OUTPUT_OPTIONS.SINGLE,+ OUTPUT_OPTIONS.MULTIPLE,+] as const;+const FIT_OPTION_VALUES = [+ FIT_OPTIONS.FIT_PAGE,+ FIT_OPTIONS.MAINTAIN_ASPECT,+ FIT_OPTIONS.FILL_PAGE,+] as const;++/**+ * How each convert endpoint's stored options map back into the tool's parameter groups, keyed by the+ * endpoint the step targets. Only endpoints carrying configurable options appear; the rest are fully+ * described by their from/to pair. `/api/v1/convert/pdf/pdfa` backs both PDF/A and PDF/X, so its+ * reader takes the target extension to tell them apart. Groups a reader omits fall back to defaults+ * via the merge in deserializeToolStep.+ */+const CONVERT_OPTION_READERS: ConvertOptionReaders = {+ "/api/v1/convert/pdf/img": (body) => ({+ imageOptions: {+ ...defaultParameters.imageOptions,+ colorType: asEnum(+ body.colorType,+ COLOR_TYPE_VALUES,+ defaultParameters.imageOptions.colorType,+ ),+ dpi: asInt(body.dpi, defaultParameters.imageOptions.dpi),+ singleOrMultiple: asEnum(+ body.singleOrMultiple,+ OUTPUT_OPTION_VALUES,+ defaultParameters.imageOptions.singleOrMultiple,+ ),+ },+ }),+ "/api/v1/convert/img/pdf": (body) => ({+ imageOptions: {+ ...defaultParameters.imageOptions,+ fitOption: asEnum(+ body.fitOption,+ FIT_OPTION_VALUES,+ defaultParameters.imageOptions.fitOption,+ ),+ colorType: asEnum(+ body.colorType,+ COLOR_TYPE_VALUES,+ defaultParameters.imageOptions.colorType,+ ),+ autoRotate: asFlag(body.autoRotate),+ },+ }),+ "/api/v1/convert/svg/pdf": (body) => ({+ imageOptions: {+ ...defaultParameters.imageOptions,+ combineImages: asFlag(body.combineIntoSinglePdf),+ },+ }),+ "/api/v1/convert/html/pdf": (body) => ({+ htmlOptions: {+ zoomLevel: asInt(body.zoom, defaultParameters.htmlOptions.zoomLevel),+ },+ }),+ "/api/v1/convert/eml/pdf": (body) => ({+ emailOptions: {+ includeAttachments: asFlag(body.includeAttachments),+ maxAttachmentSizeMB: asInt(+ body.maxAttachmentSizeMB,+ defaultParameters.emailOptions.maxAttachmentSizeMB,+ ),+ downloadHtml: asFlag(body.downloadHtml),+ includeAllRecipients: asFlag(body.includeAllRecipients),+ },+ }),+ "/api/v1/convert/pdf/pdfa": (body, toExtension) =>+ toExtension === "pdfx"+ ? {+ pdfxOptions: {+ outputFormat:+ body.outputFormat ?? defaultParameters.pdfxOptions.outputFormat,+ },+ }+ : {+ pdfaOptions: {+ outputFormat:+ body.outputFormat ?? defaultParameters.pdfaOptions.outputFormat,+ strict: asFlag(body.strict),+ },+ },+ "/api/v1/convert/cbr/pdf": (body) => ({+ cbrOptions: { optimizeForEbook: asFlag(body.optimizeForEbook) },+ }),+ "/api/v1/convert/pdf/cbr": (body) => ({+ pdfToCbrOptions: {+ dpi: asInt(body.dpi, defaultParameters.pdfToCbrOptions.dpi),+ },+ }),+ "/api/v1/convert/cbz/pdf": (body) => ({+ cbzOptions: { optimizeForEbook: asFlag(body.optimizeForEbook) },+ }),+ "/api/v1/convert/pdf/cbz": (body) => ({+ cbzOutputOptions: {+ dpi: asInt(body.dpi, defaultParameters.cbzOutputOptions.dpi),+ },+ }),+ "/api/v1/convert/ebook/pdf": (body) => ({+ ebookOptions: {+ embedAllFonts: asFlag(body.embedAllFonts),+ includeTableOfContents: asFlag(body.includeTableOfContents),+ includePageNumbers: asFlag(body.includePageNumbers),+ optimizeForEbook: asFlag(body.optimizeForEbook),+ },+ }),+ "/api/v1/convert/pdf/epub": (body) => {+ const fallback = defaultParameters.epubOptions;+ return {+ epubOptions: {+ detectChapters:+ body.detectChapters !== undefined+ ? asFlag(body.detectChapters)+ : (fallback?.detectChapters ?? true),+ targetDevice:+ body.targetDevice ?? fallback?.targetDevice ?? "TABLET_PHONE_IMAGES",+ outputFormat: body.outputFormat ?? fallback?.outputFormat ?? "EPUB",+ },+ };+ },+};++/**+ * Rebuild the tool's UI parameters from a stored convert step: recover the conversion from the+ * `fromExtension`/`toExtension` bookkeeping, resolve the endpoint it targeted, then hand its stored+ * options to that endpoint's reader. Re-opening a saved step shows exactly what was configured (and+ * re-saving it doesn't reset options to defaults). The generated request models can't type this: a+ * stored value is always a string, and two convert models (colorType, fitOption) declare the backend+ * spelling rather than the value the tool sends today - so options are validated against the+ * frontend's own option sets instead.+ */+export const convertFromApiParams = (+ apiParams: ToolApiParams[ToolEndpoint],+): Partial<ConvertParameters> => {+ const body = apiParams as unknown as Record<string, string | undefined>;+ const fromExtension = body.fromExtension ?? "";+ const toExtension = body.toExtension ?? "";+ const endpoint = convertEndpointFor(fromExtension, toExtension);+ // Each reader reads only its own endpoint's fields; the runtime endpoint is just a string, so the+ // precise per-endpoint type is recovered with one widening cast here (every reader accepts a+ // superset string record).+ const readOptions = endpoint+ ? (CONVERT_OPTION_READERS[endpoint] as ConvertOptionReader | undefined)+ : undefined;+ return {+ fromExtension,+ toExtension,+ ...(readOptions ? readOptions(body, toExtension) : {}),+ };+};+// Static configuration objectexport const convertOperationConfig = defineCustomTool({validateParams: validateConvertParameters,customProcessor: convertProcessor, // Can't use callback version hereoperationType: "convert",defaultParameters,- endpoint: (params: ConvertParameters): string | undefined => {- if (!params.fromExtension || !params.toExtension) return undefined;- const actualToExtension =- params.toExtension === "pdfx" ? "pdfa" : params.toExtension;- return getEndpointUrl(params.fromExtension, actualToExtension) ?? undefined;- },+ endpoint: (params: ConvertParameters): string | undefined =>+ convertEndpointFor(params.fromExtension, params.toExtension),+ // Routing set for a dynamic endpoint, so a stored convert step maps back to this tool.+ endpoints: CONVERT_AUTOMATION_ENDPOINTS,+ toApiParams: convertToApiParams,+ fromApiParams: convertFromApiParams,});export const useConvertOperation = (parameters?: ConvertParameters) => {diff --git a/frontend/editor/src/core/hooks/tools/shared/toolAutomation.test.ts b/frontend/editor/src/core/hooks/tools/shared/toolAutomation.test.tsindex e8d34ef9ad..5be4831907 100644--- a/frontend/editor/src/core/hooks/tools/shared/toolAutomation.test.ts+++ b/frontend/editor/src/core/hooks/tools/shared/toolAutomation.test.ts@@ -26,6 +26,8 @@ import { autoRotateOperationConfig } from "@app/hooks/tools/autoRotate/useAutoRoimport { defaultParameters as autoRotateDefaults } from "@app/hooks/tools/autoRotate/useAutoRotateParameters";import { addPasswordOperationConfig } from "@app/hooks/tools/addPassword/useAddPasswordOperation";import { changePermissionsOperationConfig } from "@app/hooks/tools/changePermissions/useChangePermissionsOperation";+import { convertOperationConfig } from "@app/hooks/tools/convert/useConvertOperation";+import { defaultParameters as convertDefaults } from "@app/hooks/tools/convert/useConvertParameters";function entry(over: Partial<ToolRegistryEntry>): ToolRegistryEntry {return {@@ -296,6 +298,127 @@ describe("shared-endpoint disambiguation", () => {}});+describe("convert (format-routed custom tool)", () => {+ const convertRegistry: Partial<ToolRegistry> = {+ convert: entry({+ name: "Convert",+ automationSettings: NoopSettings,+ operationConfig: asRegistryConfig(convertOperationConfig),+ }),+ };++ test("is offered as an editable step despite an unresolved default endpoint", () => {+ const tools = getExecutableTools(convertRegistry);+ expect(tools.map((t) => t.toolId)).toEqual(["convert"]);+ expect(tools[0].support).toBe("editable");+ // Its from/to are unset by default, so a representative endpoint stands in for the picker.+ expect(tools[0].endpoint).toBe("/api/v1/convert/file/pdf");+ expect(tools[0].endpoints).toContain("/api/v1/convert/pdf/word");+ });++ test("round-trips a PDF -> Word step, carrying from/to and the output format", () => {+ const step: WorkingToolStep = {+ toolId: "convert" as ToolId,+ operation: "/api/v1/convert/file/pdf",+ params: { ...convertDefaults, fromExtension: "pdf", toExtension: "docx" },+ support: "editable",+ };++ const api = serializeToolStep(step, convertRegistry);+ expect(api.operation).toBe("/api/v1/convert/pdf/word");+ expect(api.parameters).toMatchObject({+ fromExtension: "pdf",+ toExtension: "docx",+ outputFormat: "docx",+ });++ const back = deserializeToolStep(api, convertRegistry);+ expect(back.toolId).toBe("convert");+ expect(back.support).toBe("editable");+ expect(back.operation).toBe("/api/v1/convert/pdf/word");+ expect(back.params).toMatchObject({+ fromExtension: "pdf",+ toExtension: "docx",+ });+ });++ test("round-trips a PDF -> image step, restoring the image options", () => {+ const step: WorkingToolStep = {+ toolId: "convert" as ToolId,+ operation: "/api/v1/convert/file/pdf",+ params: {+ ...convertDefaults,+ fromExtension: "pdf",+ toExtension: "png",+ imageOptions: { ...convertDefaults.imageOptions, dpi: 600 },+ },+ support: "editable",+ };++ const api = serializeToolStep(step, convertRegistry);+ expect(api.operation).toBe("/api/v1/convert/pdf/img");+ expect(api.parameters).toMatchObject({ imageFormat: "png", dpi: "600" });++ const back = deserializeToolStep(api, convertRegistry);+ expect(back.operation).toBe("/api/v1/convert/pdf/img");+ expect(back.params).toMatchObject({+ toExtension: "png",+ imageOptions: { dpi: 600 },+ });+ });++ test("round-trips an image -> PDF step, restoring the from-image options", () => {+ const step: WorkingToolStep = {+ toolId: "convert" as ToolId,+ operation: "/api/v1/convert/file/pdf",+ params: {+ ...convertDefaults,+ fromExtension: "png",+ toExtension: "pdf",+ imageOptions: {+ ...convertDefaults.imageOptions,+ fitOption: "fillPage",+ autoRotate: false,+ },+ },+ support: "editable",+ };++ const api = serializeToolStep(step, convertRegistry);+ expect(api.operation).toBe("/api/v1/convert/img/pdf");+ expect(api.parameters).toMatchObject({+ fitOption: "fillPage",+ autoRotate: "false",+ });++ const back = deserializeToolStep(api, convertRegistry);+ expect(back.params).toMatchObject({+ imageOptions: { fitOption: "fillPage", autoRotate: false },+ });+ });++ test("routes PDF/X through the shared PDF/A endpoint and recovers the PDF/X target", () => {+ const step: WorkingToolStep = {+ toolId: "convert" as ToolId,+ operation: "/api/v1/convert/file/pdf",+ params: { ...convertDefaults, fromExtension: "pdf", toExtension: "pdfx" },+ support: "editable",+ };++ const api = serializeToolStep(step, convertRegistry);+ // PDF/X has no endpoint of its own; it rides the PDF/A endpoint, distinguished by the bookkeeping.+ expect(api.operation).toBe("/api/v1/convert/pdf/pdfa");+ expect(api.parameters).toMatchObject({ toExtension: "pdfx" });++ const back = deserializeToolStep(api, convertRegistry);+ expect(back.operation).toBe("/api/v1/convert/pdf/pdfa");+ expect(back.params).toMatchObject({+ toExtension: "pdfx",+ pdfxOptions: { outputFormat: "pdfx" },+ });+ });+});+describe("stepRequiresUpload", () => {const step = (params: Record<string, unknown>): WorkingToolStep => ({toolId: "compress" as ToolId,diff --git a/frontend/editor/src/core/hooks/tools/shared/toolAutomation.ts b/frontend/editor/src/core/hooks/tools/shared/toolAutomation.tsindex b32f783b06..0485791f15 100644--- a/frontend/editor/src/core/hooks/tools/shared/toolAutomation.ts+++ b/frontend/editor/src/core/hooks/tools/shared/toolAutomation.ts@@ -45,6 +45,12 @@ export interface ExecutableTool {subcategoryId: SubcategoryId;/** Endpoint resolved from default parameters, for display/inclusion. The stored step's endpoint is re-resolved from the configured parameters at serialization time. */endpoint: ToolEndpoint;+ /**+ * For a format-routed tool (one dynamic endpoint over a declared set, e.g. convert), the full set+ * it may resolve to. A picker can then judge compatibility against any of them rather than the one+ * representative `endpoint`. Absent for a single-endpoint tool.+ */+ endpoints?: readonly ToolEndpoint[];support: ToolStepSupport;}@@ -158,9 +164,10 @@ export function stepNeedsConfiguring(}/**- * The tools that can be run as a backend operation step, sorted by name. Includes only automatable- * tools whose endpoint resolves from defaults (so they can become a backend step); this drops- * tools with no operationConfig and tools whose endpoint needs runtime input (e.g. convert).+ * The tools that can be run as a backend operation step, sorted by name. Includes automatable tools+ * whose endpoint resolves from defaults, plus format-routed tools (e.g. convert) whose endpoint only+ * resolves once configured but that declare their routing set - represented by the first endpoint of+ * that set. Drops tools with no operationConfig and no way to name a backend endpoint at all.*/export function getExecutableTools(registry: Partial<ToolRegistry>,@@ -170,7 +177,11 @@ export function getExecutableTools(if (!entry || !getToolSupportsAutomate(entry)) continue;const config = entry.operationConfig;if (!config) continue;- const endpoint = resolveEndpoint(config, config.defaultParameters ?? {});+ // A configured endpoint from defaults, else the routing set's first member as a stand-in so a+ // tool that only resolves once the user picks (convert's from/to) can still be offered.+ const endpoint =+ resolveEndpoint(config, config.defaultParameters ?? {}) ??+ config.endpoints?.find(isToolEndpoint);if (!endpoint) continue;tools.push({toolId: id as ToolId,@@ -178,6 +189,7 @@ export function getExecutableTools(icon: entry.icon,subcategoryId: entry.subcategoryId,endpoint,+ endpoints: config.endpoints,support: classifyToolStepSupport(entry),});}@@ -198,6 +210,27 @@ export function newWorkingToolStep(};}+/**+ * Apply edited parameters to a working step, re-resolving its endpoint from them. A format-routed+ * tool changes which endpoint it targets as its routing parameters change (convert's from/to,+ * split's method), so the working step's `operation` must track the params to keep live chain+ * validation and the carried output format honest - not just at serialization time. The operation+ * is left unchanged when the new params don't resolve one, or the step maps to no known tool.+ */+export function updateWorkingStepParams(+ step: WorkingToolStep,+ params: ErasedToolParams,+ registry: Partial<ToolRegistry>,+): WorkingToolStep {+ const next = { ...step, params };+ if (next.toolId === null) return next;+ const config = registry[next.toolId]?.operationConfig;+ if (!config) return next;+ const merged = { ...(config.defaultParameters ?? {}), ...params };+ const operation = resolveEndpoint(config, merged);+ return operation ? { ...next, operation } : next;+}+/** Serialize a working step into the backend step contract (endpoint + backend parameters). */export function serializeToolStep(step: WorkingToolStep,diff --git a/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.ts b/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.tsindex d1f306a3f0..d6dbf3b355 100644--- a/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.ts+++ b/frontend/editor/src/core/hooks/tools/shared/toolOperationTypes.ts@@ -173,8 +173,14 @@ export interface CustomToolOperationConfig<*/endpoint?: string | ((params: TParams) => string | undefined);- /** `never` so `endpoints` stays readable across the union; custom tools declare no set. */- endpoints?: never;+ /**+ * The full set of endpoints a dynamic (function) `endpoint` may resolve to. A custom tool whose+ * endpoint is chosen from frontend-only parameters (e.g. convert's from/to selectors) declares it+ * so a stored step maps back to this tool by endpoint membership - see findToolByEndpoint - which+ * replaying the endpoint function against the stored body alone could not recover. Omit for a+ * static endpoint.+ */+ endpoints?: readonly ToolEndpoint[];/*** Custom processing logic that completely bypasses standard file processing.diff --git a/frontend/editor/src/core/tools/Convert.tsx b/frontend/editor/src/core/tools/Convert.tsxindex b1d214f1a6..eb9a4a02c5 100644--- a/frontend/editor/src/core/tools/Convert.tsx+++ b/frontend/editor/src/core/tools/Convert.tsx@@ -1,8 +1,10 @@import { useEffect, useRef } from "react";import { useTranslation } from "react-i18next";import { useEndpointEnabled } from "@app/hooks/useEndpointConfig";-import { useAllFiles } from "@app/contexts/FileContext";+import { useAllFiles, useFileSelection } from "@app/contexts/FileContext";import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";+import { detectFileExtension } from "@app/utils/fileUtils";+import { isImageFormat } from "@app/utils/convertUtils";import { createToolFlow } from "@app/components/tools/shared/createToolFlow";@@ -15,7 +17,25 @@ import { BaseToolProps, ToolComponent } from "@app/types/tool";const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {const { t } = useTranslation();const { files: activeFiles } = useAllFiles();+ const { setSelectedFiles } = useFileSelection();const selectedFiles = useViewScopedFiles();++ // Selecting a source format narrows the working selection to the loaded files that match it. This+ // is an editor convenience; ConvertSettings itself is FileContext-free so it can also render in+ // the automation and pipeline surfaces, which have no loaded files.+ const handleSourceFormatSelected = (fromExtension: string) => {+ if (activeFiles.length === 0) {+ setSelectedFiles([]);+ return;+ }+ const matching = activeFiles.filter((file) => {+ const ext = detectFileExtension(file.name);+ if (fromExtension === "any") return true;+ if (fromExtension === "image") return isImageFormat(ext);+ return ext === fromExtension;+ });+ setSelectedFiles(matching.map((file) => file.fileId));+ };const scrollContainerRef = useRef<HTMLDivElement>(null);const convertParams = useConvertParameters();@@ -157,6 +177,7 @@ const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {onParameterChange={convertParams.updateParameter}getAvailableToExtensions={convertParams.getAvailableToExtensions}selectedFiles={selectedFiles}+ onSourceFormatSelected={handleSourceFormatSelected}disabled={endpointLoading}/>),diff --git a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.test.tsx b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.test.tsxindex 698fb0028a..946e24b810 100644--- a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.test.tsx+++ b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.test.tsx@@ -1,12 +1,24 @@import { describe, expect, it, vi } from "vitest";+import { useEffect, useState } from "react";import { render, screen } from "@testing-library/react";-import { MantineProvider } from "@mantine/core";+import { PortalTestProviders } from "@portal/test/TestQueryProvider";import { Tooltip } from "@app/components/shared/Tooltip";import type { ToolRegistry } from "@app/data/toolsTaxonomy";import type { WorkingToolStep } from "@app/hooks/tools/shared/toolAutomation";+import {+ asRegistryConfig,+ type ErasedToolParams,+ type ToolAutomationSettingsProps,+} from "@app/hooks/tools/shared/toolOperationTypes";+import ConvertSettings from "@app/components/tools/convert/ConvertSettings";+import { convertOperationConfig } from "@app/hooks/tools/convert/useConvertOperation";+import { defaultParameters as convertDefaults } from "@app/hooks/tools/convert/useConvertParameters";import { PipelineStepSettings } from "@portal/components/pipelines/PipelineStepSettings";-vi.mock("react-i18next", () => ({+// Override only useTranslation; keep the rest of react-i18next (initReactI18next et al.) real, so+// the convert settings' transitive i18n setup still initializes.+vi.mock("react-i18next", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react-i18next")>()),useTranslation: () => ({t: (key: string, fallback?: string) => fallback ?? key,}),@@ -34,19 +46,105 @@ const registry = {compress: { automationSettings: TooltipSettings },} as unknown as Partial<ToolRegistry>;+// The real Convert tool settings, wired as they are in the registry. ConvertSettings was decoupled+// from the editor's FileContext so it can render here (the portal mounts no FileProvider); this+// pins that it renders its format selectors instead of crashing on a missing context.+const convertStep = {+ support: "editable",+ toolId: "convert",+ operation: "/api/v1/convert/pdf/word",+ params: convertDefaults,+} as unknown as WorkingToolStep;++const convertRegistry = {+ convert: {+ automationSettings: ConvertSettings,+ operationConfig: asRegistryConfig(convertOperationConfig),+ },+} as unknown as Partial<ToolRegistry>;+describe("PipelineStepSettings", () => {it("renders reused editor tool settings (which use the shared Tooltip) without app-wide Preferences/Sidebar providers", () => {expect(() =>render(- <MantineProvider>+ <PortalTestProviders><PipelineStepSettingsstep={step}registry={registry}onChange={() => {}}/>- </MantineProvider>,+ </PortalTestProviders>,),).not.toThrow();expect(screen.getByText("field")).toBeInTheDocument();});++ it("renders the Convert tool's format selectors in the portal, with no FileContext mounted", () => {+ expect(() =>+ render(+ <PortalTestProviders>+ <PipelineStepSettings+ step={convertStep}+ registry={convertRegistry}+ onChange={() => {}}+ />+ </PortalTestProviders>,+ ),+ ).not.toThrow();+ expect(screen.getByText(/Convert from/)).toBeInTheDocument();+ });++ // Reproduces the convert-in-pipeline bug: picking a source format fires several onParameterChange+ // calls in one tick (set fromExtension, auto-target, reset options). If each rebuilt from the+ // step snapshot captured at render they'd clobber each other and the earlier field would be lost.+ it("accumulates several synchronous field changes instead of keeping only the last", () => {+ function DoubleWriteSettings({+ onParameterChange,+ }: ToolAutomationSettingsProps<ErasedToolParams>) {+ // Fire once on mount, mimicking a source-format change's burst of synchronous updates.+ useEffect(() => {+ onParameterChange("fromExtension", "pdf");+ onParameterChange("toExtension", "docx");+ }, []);+ return null;+ }++ const registry = {+ doubleWrite: { automationSettings: DoubleWriteSettings },+ } as unknown as Partial<ToolRegistry>;++ function Harness() {+ const [params, setParams] = useState<ErasedToolParams>({});+ const step = {+ toolId: "doubleWrite",+ support: "editable",+ operation: "/api/v1/x",+ params,+ } as unknown as WorkingToolStep;+ return (+ <>+ <PipelineStepSettings+ step={step}+ registry={registry}+ onChange={(update) =>+ setParams((prev) =>+ typeof update === "function" ? update(prev) : update,+ )+ }+ />+ <span data-testid="out">{JSON.stringify(params)}</span>+ </>+ );+ }++ render(+ <PortalTestProviders>+ <Harness />+ </PortalTestProviders>,+ );+ expect(JSON.parse(screen.getByTestId("out").textContent ?? "{}")).toEqual({+ fromExtension: "pdf",+ toExtension: "docx",+ });+ });});diff --git a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsxindex 213217de5b..58fb2a96fa 100644--- a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx+++ b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx@@ -11,10 +11,20 @@ import { PolicyExternalApiConfig } from "@portal/components/policies/PolicyExterimport { isIntegrationStep } from "@portal/components/pipelines/integrationStep";import type { ExternalApiStepParams } from "@portal/components/policies/stepOperations";+/**+ * A params update: the next params outright, or a merge from the latest params. Settings UIs fire+ * several single-field changes synchronously (e.g. convert's source-format change also resets the+ * target and options); the merge form lets them accumulate against current state instead of each+ * rebuilding from the `step` snapshot captured at render, which would clobber the earlier fields.+ */+export type ParamsUpdate =+ | ErasedToolParams+ | ((prev: ErasedToolParams) => ErasedToolParams);+interface PipelineStepSettingsProps {step: WorkingToolStep;registry: Partial<ToolRegistry>;- onChange: (params: ErasedToolParams) => void;+ onChange: (update: ParamsUpdate) => void;}/**@@ -71,7 +81,7 @@ export function PipelineStepSettings({<Settingsparameters={step.params}onParameterChange={(key, value) =>- onChange({ ...step.params, [key]: value })+ onChange((prev) => ({ ...prev, [key]: value }))}disabled={false}/>diff --git a/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx b/frontend/editor/src/portal/components/pipelines/ToolPicker.tsxindex 09f4625c99..03bd941475 100644--- a/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx+++ b/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx@@ -51,6 +51,20 @@ export function ToolPicker({const { t } = useTranslation();const [query, setQuery] = useState("");+ // A format-routed tool (convert) can follow the previous step if ANY endpoint in its routing set+ // accepts that output; a single-endpoint tool is judged on its one endpoint. Unknown when there+ // is no preceding output yet.+ const acceptsPreceding = (tool: ExecutableTool): boolean => {+ if (!precedingOutput) return true;+ const endpoints =+ tool.endpoints && tool.endpoints.length > 0+ ? tool.endpoints+ : [tool.endpoint];+ return endpoints.some((endpoint) =>+ toolAcceptsFormat(endpoint, precedingOutput),+ );+ };+const matchedOperations = useMemo(() =>onPickOperation@@ -106,8 +120,7 @@ export function ToolPicker({</div>{group.tools.map((tool) => {const incompatible = Boolean(- precedingOutput &&- !toolAcceptsFormat(tool.endpoint, precedingOutput),+ precedingOutput && !acceptsPreceding(tool),);return (<Buttondiff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsxindex 24d215a99f..b1ff80682d 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx@@ -406,6 +406,21 @@ describe("PipelineBuilder", () => {).toBeDisabled();});+ it("stays quiet on the wires around a step that still needs setting up", async () => {+ renderBuilder("/processor/pipelines/new");+ await addTool("OCR");++ // The node itself flags that it needs setting up...+ await screen.findByText("portal.pipelines.builder.needsConfiguring");+ // ...but the wires around it don't nag: an unconfigured step's operation is unknown, so neither+ // the wire into it nor the one out of it shows a compatibility warning until it is configured.+ expect(+ screen.queryByText(+ "portal.pipelines.builder.diagnostic.undeclared-operation",+ ),+ ).not.toBeInTheDocument();+ });+it("clears the warning once the step is configured", async () => {renderBuilder("/processor/pipelines/new");await addTool("OCR");diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsxindex ecc249d88e..746fd61ab0 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx@@ -16,7 +16,6 @@ import {Spinner,} from "@app/ui";import { useToolRegistry } from "@app/contexts/ToolRegistryContext";-import { type ErasedToolParams } from "@app/hooks/tools/shared/toolOperationTypes";import {deserializeToolStep,getExecutableTools,@@ -24,6 +23,7 @@ import {serializeToolStep,stepNeedsConfiguring,stepRequiresUpload,+ updateWorkingStepParams,type ExecutableTool,type WorkingToolStep,} from "@app/hooks/tools/shared/toolAutomation";@@ -78,7 +78,10 @@ import {type GraphSelection,type GraphStepContent,} from "@portal/components/pipelines/graph/PipelineGraph";-import { PipelineStepSettings } from "@portal/components/pipelines/PipelineStepSettings";+import {+ PipelineStepSettings,+ type ParamsUpdate,+} from "@portal/components/pipelines/PipelineStepSettings";import { ToolPicker } from "@portal/components/pipelines/ToolPicker";import { BrandMark } from "@portal/components/BrandMarks";import { STEP_OPERATIONS } from "@portal/components/policies/stepOperations";@@ -453,15 +456,22 @@ export function PipelineBuilder() {setSelected(landed.length > 0 ? { steps: landed } : null);}- function updateStepParams(index: number, params: ErasedToolParams) {+ function updateStepParams(index: number, update: ParamsUpdate) {setSteps((current) =>- current.map((step, i) =>+ current.map((step, i) => {// Integration steps are deliberately toolId-less, so they must be editable too; only a// genuinely unrecognised step has no editor to send changes from.- i === index && (step.toolId !== null || isIntegrationStep(step))- ? { ...step, params }- : step,- ),+ if (i !== index || (step.toolId === null && !isIntegrationStep(step)))+ return step;+ // Resolve the update against the CURRENT step params, so a settings UI firing several+ // single-field changes in one tick (convert's source-format change resets target + options)+ // accumulates instead of each merge clobbering a stale snapshot. updateWorkingStepParams+ // also re-resolves the endpoint for a format-routed tool so validation reflects the edit;+ // it's a no-op on the operation for fixed-endpoint steps.+ const nextParams =+ typeof update === "function" ? update(step.params) : update;+ return updateWorkingStepParams(step, nextParams, allTools);+ }),);}@@ -508,18 +518,28 @@ export function PipelineBuilder() {.map(stepLabel);const hasUnconfiguredSteps = unconfiguredStepLabels.length > 0;+ // Steps as the I/O checker sees them. A step still needing configuration has no settled endpoint+ // yet (a format-routed tool like convert doesn't know its from/to), so it is presented as+ // undeclared: it raises no compatibility error and breaks the carry chain, leaving downstream+ // steps unjudged until it is filled in. Its own "needs configuring" note already flags it.+ const validationSteps = useMemo(+ () =>+ steps.map((step) => ({+ operation: stepNeedsConfiguring(step, allTools) ? "" : step.operation,+ parameters: step.params,+ })),+ [steps, allTools],+ );+// Whether each step can actually accept what the one before it produces. Checked here from the// generated tool I/O table rather than by running the pipeline, so an impossible chain (say,// Extract Images then Rotate) is caught while it is being built.const chainDiagnostics = useMemo(() =>- validateToolChain(- steps.map((step) => ({- operation: step.operation,- parameters: step.params,- })),+ validateToolChain(validationSteps).filter(+ (d) => !stepNeedsConfiguring(steps[d.stepIndex], allTools),),- [steps],+ [validationSteps, steps, allTools],);const blockingSteps = chainDiagnostics.filter((d) => d.severity === "ERROR")@@ -529,19 +549,16 @@ export function PipelineBuilder() {/*** What a step added at the open slot would be handed, so the picker can flag tools that cannot* take it. Scoped to the steps *before* that slot rather than the whole chain: the graph inserts- * anywhere, so what precedes the new step is not necessarily the chain's final output.+ * anywhere, so what precedes the new step is not necessarily the chain's final output. Sliced from+ * the validation view so an unconfigured step before the slot yields an unknown (undefined) format+ * rather than a misleading one from its placeholder endpoint.*/const precedingOutput = useMemo(() =>pickerAt === null? undefined- : chainOutputFormat(- steps.slice(0, pickerAt).map((step) => ({- operation: step.operation,- parameters: step.params,- })),- ),- [steps, pickerAt],+ : chainOutputFormat(validationSteps.slice(0, pickerAt)),+ [validationSteps, pickerAt],);function diagnosticNote(diagnostic: ToolDiagnostic): string {