#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
Only run pipelines/policies on files of appropriate type in editor (#8000)
James Brunton5ad919d23b9a
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsxindex c48fa210d9..572afff8ac 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx@@ -92,6 +92,7 @@ vi.mock("@app/hooks/usePolicies", () => ({runsOnEditor: true,enabled: true,backendId: "backend-security",+ firstOperation: "/api/v1/misc/compress-pdf",runOn: securityRunOn.value,order: 1,outputMode: "new_version",diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsxindex 60a81b490c..49a44865e4 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx@@ -1,12 +1,27 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { renderHook, act } from "@testing-library/react";+import type { PolicyState } from "@app/types/policies";// Two active file-producing upload policies, so the auto-run should CHAIN them: fire the first on// the upload, then the second on the first's output. A classification policy is also present to// assert the engine leaves it alone - annotating policies run themselves (see useClassificationPolicy),// so they are never in this server chain. Stub the contexts + network to drive dispatch against the// REAL run store.-const fileStubs: { id: string; name: string; derivedFromTool?: boolean }[] = [];+const inputOperations = vi.hoisted<{+ security: PolicyState["firstOperation"];+ compliance: PolicyState["firstOperation"];+ archiveEnabled: boolean;+}>(() => ({+ security: "/api/v1/misc/compress-pdf",+ compliance: "/api/v1/misc/compress-pdf",+ archiveEnabled: false,+}));+const fileStubs: {+ id: string;+ name: string;+ derivedFromTool?: boolean;+ classificationLocked?: boolean;+}[] = [];vi.mock("@app/contexts/FileContext", () => ({useAllFiles: () => ({ fileStubs }),useFileManagement: () => ({ addFiles: vi.fn() }),@@ -20,6 +35,7 @@ vi.mock("@app/hooks/usePolicies", () => ({runsOnEditor: true,enabled: true,backendId: "backend-sec",+ firstOperation: inputOperations.security,runOn: "upload",order: 0,},@@ -28,6 +44,7 @@ vi.mock("@app/hooks/usePolicies", () => ({runsOnEditor: true,enabled: true,backendId: "backend-comp",+ firstOperation: inputOperations.compliance,runOn: "upload",order: 1,},@@ -39,6 +56,15 @@ vi.mock("@app/hooks/usePolicies", () => ({runOn: "upload",order: 2,},+ archive: {+ configured: true,+ runsOnEditor: true,+ enabled: inputOperations.archiveEnabled,+ backendId: "backend-archive",+ firstOperation: "/api/v1/convert/img/pdf",+ runOn: "upload",+ order: 3,+ },},}),}));@@ -104,13 +130,203 @@ beforeEach(() => {localStorage.clear();resetPolicyRuns();setFileStubs([]);+ inputOperations.security = "/api/v1/misc/compress-pdf";+ inputOperations.compliance = "/api/v1/misc/compress-pdf";+ inputOperations.archiveEnabled = false;runStored.mockReset();getFile.mockReset();getFile.mockResolvedValue({ size: 100 } as never);+ vi.mocked(fileStorage.getStirlingFileStub).mockImplementation(+ async (id) =>+ ({+ id,+ name: "doc.pdf",+ type: "application/pdf",+ }) as never,+ );});afterEach(() => vi.useRealTimers());describe("auto-run ordered chaining", () => {+ it("does not chain a compatible output whose classification is locked", async () => {+ completeRun("run-sec", "security", "original", ["locked", "unlocked"]);+ setFileStubs([+ {+ id: "locked",+ name: "locked.pdf",+ derivedFromTool: true,+ classificationLocked: true,+ },+ { id: "unlocked", name: "unlocked.pdf", derivedFromTool: true },+ ]);+ runStored.mockResolvedValue("run-comp");++ renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });++ expect(runStored).toHaveBeenCalledTimes(1);+ expect(runStored).toHaveBeenCalledWith(+ "backend-comp",+ expect.anything(),+ "unlocked",+ );+ expect(getFile).not.toHaveBeenCalledWith("locked");+ });++ it("resumes a completed chain once the next policy's input metadata loads", async () => {+ inputOperations.compliance = undefined;+ completeRun("run-sec", "security", "original", ["pdf"]);+ setFileStubs([{ id: "pdf", name: "report.pdf", derivedFromTool: true }]);+ runStored.mockResolvedValue("run-comp");++ const { rerender } = renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });+ expect(runStored).not.toHaveBeenCalled();++ inputOperations.compliance = "/api/v1/misc/compress-pdf";+ rerender();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });++ expect(runStored).toHaveBeenCalledTimes(1);+ expect(runStored).toHaveBeenCalledWith(+ "backend-comp",+ expect.anything(),+ "pdf",+ );+ });++ it("skips an empty pipeline without holding up a compatible one", async () => {+ inputOperations.security = null;+ setFileStubs([{ id: "pdf", name: "report.pdf" }]);+ runStored.mockResolvedValue("run-comp");++ renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });++ expect(runStored).toHaveBeenCalledTimes(1);+ expect(runStored).toHaveBeenCalledWith(+ "backend-comp",+ expect.anything(),+ "pdf",+ );+ });++ it("skips an incompatible middle policy and continues the output's chain", async () => {+ inputOperations.archiveEnabled = true;+ completeRun("run-sec", "security", "original", ["image"]);+ setFileStubs([{ id: "image", name: "page.png", derivedFromTool: true }]);+ runStored.mockResolvedValue("run-image");++ renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });++ expect(runStored).toHaveBeenCalledTimes(1);+ expect(runStored).toHaveBeenCalledWith(+ "backend-archive",+ expect.anything(),+ "image",+ );+ });+ it("dispatches only matching files from a mixed upload", async () => {+ setFileStubs([+ { id: "pdf", name: "report.PDF" },+ { id: "image", name: "scan.png" },+ { id: "word", name: "letter.docx" },+ ]);+ runStored.mockResolvedValue("run-pdf");++ const { rerender } = renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });+ rerender();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });++ expect(runStored).toHaveBeenCalledTimes(1);+ expect(runStored).toHaveBeenCalledWith(+ "backend-sec",+ expect.anything(),+ "pdf",+ );+ expect(getFile).not.toHaveBeenCalledWith("image");+ expect(getFile).not.toHaveBeenCalledWith("word");+ });++ it("starts each file at its first compatible policy in team order", async () => {+ inputOperations.security = "/api/v1/convert/img/pdf";+ setFileStubs([+ { id: "image", name: "scan.PNG" },+ { id: "pdf", name: "report.pdf" },+ { id: "word", name: "letter.docx" },+ ]);+ runStored.mockImplementation(async (id) => `run-${id}`);++ renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });++ expect(runStored.mock.calls.map(([id, , fileId]) => [id, fileId])).toEqual([+ ["backend-sec", "image"],+ ["backend-comp", "pdf"],+ ]);+ });++ it("waits for a cached pipeline's first operation before dispatching", async () => {+ inputOperations.security = undefined;+ inputOperations.compliance = "/api/v1/convert/img/pdf";+ setFileStubs([{ id: "pdf", name: "report.pdf" }]);+ runStored.mockResolvedValue("run-pdf");++ const { rerender } = renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });+ expect(runStored).not.toHaveBeenCalled();++ inputOperations.security = "/api/v1/misc/compress-pdf";+ rerender();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });+ expect(runStored).toHaveBeenCalledTimes(1);+ });++ it("checks each output's current type before chaining", async () => {+ completeRun("run-sec", "security", "original", ["image", "pdf"]);+ inputOperations.compliance = "/api/v1/convert/img/pdf";+ setFileStubs([+ { id: "image", name: "page.png", derivedFromTool: true },+ { id: "pdf", name: "report.pdf", derivedFromTool: true },+ ]);+ runStored.mockResolvedValue("run-image");++ renderHook(() => usePolicyAutoRun());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });++ expect(runStored).toHaveBeenCalledTimes(1);+ expect(runStored).toHaveBeenCalledWith(+ "backend-comp",+ expect.anything(),+ "image",+ );+ expect(getRun("run-image")?.fileName).toBe("page.png");+ });+it("dispatches only the FIRST ordered policy on upload, not the whole set", async () => {setFileStubs([{ id: "file-1", name: "doc.pdf" }]);runStored.mockResolvedValue("run-sec");diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsxindex 28853e84aa..4064305a0b 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx@@ -70,6 +70,7 @@ import { usePolicyAutoRun } from "@app/components/policies/usePolicyAutoRun";import {recordRunStart,getRun,+ updateRun,resetPolicyRuns,} from "@app/components/policies/policyRunStore";@@ -118,6 +119,20 @@ beforeEach(() => {});describe("auto-run import: new-version output delivery", () => {+ it("preserves a converted output's extension for subsequent policies", async () => {+ recordCompletedRun();+ updateRun("run-1", {+ outputs: [{ fileId: "out-file-1", fileName: "doc_converted.png" }],+ });+ mocks.downloadPolicyOutput.mockResolvedValue(new Blob(["image"]));++ await runImport();++ const file = mocks.addFiles.mock.calls[0][0][0] as File;+ expect(file.name).toBe("doc.png");+ expect(file.type).not.toBe("application/pdf");+ });+it("versions the input in storage when it's recovered after a reload (no second file)", async () => {// Reload case: the workspace is empty, but the input still persists in IndexedDB.mocks.fileStubs = [];diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsxindex 516d322338..5f10ef5966 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx@@ -23,6 +23,7 @@ vi.mock("@app/hooks/usePolicies", () => ({status: "active",enabled: true,backendId: "backend-sec",+ firstOperation: "/api/v1/misc/compress-pdf",runOn: "upload",runsOnEditor: true,order: 0,diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsxindex bfbab020fc..83579c3eb2 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.reentry.test.tsx@@ -5,7 +5,11 @@ import { renderHook, waitFor } from "@testing-library/react";// The persisted dispatch record must stop the upload policy (and its billing) firing a second time.const mocks = vi.hoisted(() => ({- workspace: [] as Array<{ id: string; derivedFromTool?: boolean }>,+ workspace: [] as Array<{+ id: string;+ name: string;+ derivedFromTool?: boolean;+ }>,runStoredPolicy: vi.fn(),getPolicyRun: vi.fn(),listPolicyRuns: vi.fn(),@@ -34,6 +38,7 @@ vi.mock("@app/hooks/usePolicies", () => ({runsOnEditor: true,enabled: true,backendId: "backend-security",+ firstOperation: "/api/v1/misc/compress-pdf",runOn: "upload",order: 0,outputMode: "new_version",@@ -88,7 +93,10 @@ beforeEach(() => {describe("upload policies and files re-entering the workbench", () => {it("does not re-run on a file the policy already ran on", async () => {markDispatched("security", "already-enforced");- mocks.workspace = [{ id: "already-enforced" }, { id: "fresh-upload" }];+ mocks.workspace = [+ { id: "already-enforced", name: "doc.pdf" },+ { id: "fresh-upload", name: "doc.pdf" },+ ];renderHook(() => usePolicyAutoRun());@@ -100,7 +108,10 @@ describe("upload policies and files re-entering the workbench", () => {it("stays silent when every file in the workbench has already been enforced", async () => {markDispatched("security", "one");markDispatched("security", "two");- mocks.workspace = [{ id: "one" }, { id: "two" }];+ mocks.workspace = [+ { id: "one", name: "doc.pdf" },+ { id: "two", name: "doc.pdf" },+ ];renderHook(() => usePolicyAutoRun());@@ -110,7 +121,9 @@ describe("upload policies and files re-entering the workbench", () => {});it("still skips a policy's own output, which is not an upload at all", async () => {- mocks.workspace = [{ id: "policy-output", derivedFromTool: true }];+ mocks.workspace = [+ { id: "policy-output", name: "doc.pdf", derivedFromTool: true },+ ];renderHook(() => usePolicyAutoRun());diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.tsindex e327d9c3b1..907f9bfa9b 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts@@ -46,6 +46,8 @@ import {policyDeliversOutputFiles,} from "@app/data/classificationPolicy";import { runPolicyOnFile } from "@app/services/policyDispatch";+import { policyAcceptsFile } from "@app/services/policyInput";+import { splitFileName } from "@app/utils/fileUtils";import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";import type { PoliciesByKey } from "@app/types/policies";import { usePolicies } from "@app/hooks/usePolicies";@@ -240,13 +242,16 @@ export function usePolicyAutoRun(): void {[scheduleQueueRetry],);- // Fire only the FIRST upload policy per file; the chaining effect below runs the rest+ // Fire only the first compatible upload policy per file; the chaining effect below runs the rest// on each previous output, so policies apply cumulatively in order.useEffect(() => {- const firstPolicyKey = orderedUploadPolicyKeys[0];- if (!firstPolicyKey) return;- const backendId = policies[firstPolicyKey]?.backendId;- if (!backendId) return;+ // An older cache has no input metadata; wait for reconciliation to preserve the team's order.+ if (+ orderedUploadPolicyKeys.some(+ (key) => policies[key].firstOperation === undefined,+ )+ )+ return;for (const stub of fileStubs) {// Input-mode policies cover uploads only; tool-produced files are left to// export-mode policies at export time.@@ -258,6 +263,12 @@ export function usePolicyAutoRun(): void {// about to decrypt, bill for it, and leave a row about a version soon replaced. Skipping// the prompt releases it, so a document nobody unlocks still records its failure.if (isAwaitingUnlock(stub.id)) continue;+ const firstPolicyKey = orderedUploadPolicyKeys.find((key) =>+ policyAcceptsFile(policies[key], stub),+ );+ if (!firstPolicyKey) continue;+ const backendId = policies[firstPolicyKey]?.backendId;+ if (!backendId) continue;const key = dispatchKey(firstPolicyKey, stub.id);// Skip if already run (persisted) or in flight - the in-memory guard covers the async wait.if (@@ -281,33 +292,26 @@ export function usePolicyAutoRun(): void {for (const run of runs) {if (run.status !== "COMPLETED" || !run.imported) continue;if (chained.current.has(run.runId)) continue;- const nextPolicyKey = nextUploadPolicyKey(- orderedUploadPolicyKeys,- run.policyKey,- );+ const index = orderedUploadPolicyKeys.indexOf(run.policyKey);+ const remainingKeys =+ index < 0 ? [] : orderedUploadPolicyKeys.slice(index + 1);+ if (+ remainingKeys.some((key) => policies[key].firstOperation === undefined)+ )+ continue;const outputIds = run.outputFileIds ?? [];- if (!nextPolicyKey || outputIds.length === 0) {+ if (remainingKeys.length === 0 || outputIds.length === 0) {// End of the chain (or nothing to chain onto): don't revisit this run.chained.current.add(run.runId);continue;}- const backendId = policies[nextPolicyKey]?.backendId;- // Next policy not ready yet (still reconciling) — retry when policies change.- if (!backendId) continue;chained.current.add(run.runId);- // Chain onto EVERY output: a run that produced several files (split, ZIP-unpacked)- // would otherwise silently skip the next policy on outputs 2..N.- for (const outputId of outputIds) {- if (isDispatched(nextPolicyKey, outputId as FileId)) continue;- // Chaining onto a run's own outputs; same reasoning as the retry above.- void runPolicyOnFile(- nextPolicyKey,- backendId,- outputId as DispatchableFileId,- run.fileName,- true, // chained → jump the dispatch queue ahead of new files- ).catch(() => {});- }+ void chainUploadPolicies(+ outputIds,+ remainingKeys,+ policies,+ fileStubsRef.current,+ ).catch(() => chained.current.delete(run.runId));}}, [runs, policies, orderedUploadPolicyKeys]);@@ -448,14 +452,30 @@ function applyOutputName(: `${base}_${outputName}${ext}`;}-/** Next upload policy in the chain, or undefined if last or no longer eligible. */-function nextUploadPolicyKey(- orderedUploadPolicyKeys: string[],- policyKey: string,-): string | undefined {- const index = orderedUploadPolicyKeys.indexOf(policyKey);- if (index < 0) return undefined;- return orderedUploadPolicyKeys[index + 1];+async function chainUploadPolicies(+ outputIds: string[],+ remainingKeys: string[],+ policies: PoliciesByKey,+ stubs: StirlingFileStub[],+): Promise<void> {+ await Promise.all(+ outputIds.map(async (outputId) => {+ // Converters and splitters can produce different types, so each output needs its own match.+ const stub =+ stubs.find((s) => s.id === outputId) ??+ (await fileStorage.getStirlingFileStub(outputId as FileId));+ if (!stub) return;+ const target = dispatchableFileId(stub);+ if (!target) return;+ const nextPolicyKey = remainingKeys.find((key) =>+ policyAcceptsFile(policies[key], stub),+ );+ if (!nextPolicyKey || isDispatched(nextPolicyKey, stub.id)) return;+ const backendId = policies[nextPolicyKey]?.backendId;+ if (!backendId) return;+ await runPolicyOnFile(nextPolicyKey, backendId, target, stub.name, true);+ }),+ );}async function reconcileServerRuns(policies: PoliciesByKey): Promise<void> {@@ -646,10 +666,13 @@ async function importOutputs(const settled = await Promise.allSettled(pending.map(async (out) => {const blob = await downloadPolicyOutput(out.fileId, run.target);+ const [base, inputExtension] = splitFileName(targetName);+ const [, outputExtension] = splitFileName(out.fileName);return {fileId: out.fileId,- file: new File([blob], targetName ?? out.fileName ?? run.fileName, {- type: blob.type || "application/pdf",+ // Conversions must retain the output extension so later policies see the resulting type.+ file: new File([blob], base + (outputExtension || inputExtension), {+ type: blob.type,}),};}),diff --git a/frontend/editor/src/proprietary/services/policyBackend.test.ts b/frontend/editor/src/proprietary/services/policyBackend.test.tsindex 5315fb77c2..cc64445bee 100644--- a/frontend/editor/src/proprietary/services/policyBackend.test.ts+++ b/frontend/editor/src/proprietary/services/policyBackend.test.ts@@ -90,6 +90,25 @@ describe("fetchPoliciesByCategory", () => {describe("decodedToState — runsOnEditor", () => {beforeEach(() => listPolicies.mockReset());+ it("carries the first stored endpoint through to editor file selection", async () => {+ const wire = policy("convert", undefined, { allowed: true });+ wire.steps = [+ { operation: "/api/v1/convert/img/pdf", parameters: {} },+ { operation: "/api/v1/misc/compress-pdf", parameters: {} },+ ];++ expect((await stateOf(wire, "convert")).firstOperation).toBe(+ "/api/v1/convert/img/pdf",+ );+ });++ it("leaves an empty pipeline without an input operation", async () => {+ const wire = policy("empty", undefined, { allowed: true });+ wire.steps = [];++ expect((await stateOf(wire, "empty")).firstOperation).toBeNull();+ });+it("runs a catalogue tile that opted into the editor", async () => {const state = await stateOf(policy("pol-1", "security", { allowed: true }),diff --git a/frontend/editor/src/proprietary/services/policyBackend.ts b/frontend/editor/src/proprietary/services/policyBackend.tsindex 01d4250636..c58d6c569c 100644--- a/frontend/editor/src/proprietary/services/policyBackend.ts+++ b/frontend/editor/src/proprietary/services/policyBackend.ts@@ -61,6 +61,7 @@ export function decodedToState(runOn: decoded.folder.runOn,folderId: localFolderId,backendId: decoded.id,+ firstOperation: decoded.firstOperation,// Server-side run-order position (team-wide); drives the settings reorder list.order: decoded.order,// Catalog-category policies are built-in defaults (not deletable); a builder pipeline is not.diff --git a/frontend/editor/src/proprietary/services/policyExport.test.ts b/frontend/editor/src/proprietary/services/policyExport.test.tsindex 8452698476..e2b28c69d0 100644--- a/frontend/editor/src/proprietary/services/policyExport.test.ts+++ b/frontend/editor/src/proprietary/services/policyExport.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from "vitest";+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import type { PoliciesByKey, PolicyState } from "@app/types/policies";// Which policies export-time enforcement picks up: the policy's own editor flag, not its scope.@@ -8,16 +8,17 @@ vi.mock("@app/services/policyStorage", () => ({loadPolicies: () => loadPolicies(),}));-const runStoredPolicy = vi.fn(async (_id: string) => "run-1");+const runStoredPolicy = vi.fn(async (_id: string, _files: File[]) => "run-1");+const output = { name: "doc.pdf", type: "application/pdf" };vi.mock("@app/services/policyApi", () => ({- runStoredPolicy: (id: string) => runStoredPolicy(id),+ runStoredPolicy: (id: string, files: File[]) => runStoredPolicy(id, files),// One output, so a run completes rather than throwing "produced no output" - which would abort// the per-file policy loop after the first policy and hide the order under test.getPolicyRun: async () => ({status: "COMPLETED",- outputs: [{ fileId: "out-1", fileName: "doc.pdf" }],+ outputs: [{ fileId: "out-1", fileName: output.name }],}),- downloadPolicyOutput: async () => new Blob(),+ downloadPolicyOutput: async () => new Blob([], { type: output.type }),resolvePolicyRunTarget: () => "local",}));@@ -44,6 +45,7 @@ const exportPolicy = (over: Partial<PolicyState>): PolicyState =>configured: true,enabled: true,backendId: "backend-1",+ firstOperation: "/api/v1/misc/compress-pdf",sources: [],runsOnEditor: false,scopeTypes: [],@@ -60,7 +62,69 @@ const pdf = () =>new File(["%PDF-1.4"], "doc.pdf", { type: "application/pdf" });describe("export-time policy selection", () => {- beforeEach(() => runStoredPolicy.mockClear());+ beforeEach(() => {+ vi.useFakeTimers();+ runStoredPolicy.mockClear();+ output.name = "doc.pdf";+ output.type = "application/pdf";+ });+ afterEach(() => vi.useRealTimers());++ it("selects each pipeline by its first input and rechecks converted outputs", async () => {+ const image = new File(["image"], "scan.PNG", { type: "image/png" });+ const word = new File(["word"], "letter.docx");+ loadPolicies.mockReturnValue({+ image: exportPolicy({+ runsOnEditor: true,+ backendId: "image",+ order: 0,+ firstOperation: "/api/v1/convert/img/pdf",+ }),+ pdf: exportPolicy({+ runsOnEditor: true,+ backendId: "pdf",+ order: 1,+ }),+ laterImage: exportPolicy({+ runsOnEditor: true,+ backendId: "later-image",+ order: 2,+ firstOperation: "/api/v1/convert/img/pdf",+ }),+ });+ output.type = "";++ const enforcement = enforceExportPolicies([pdf(), image, word]);+ await vi.runAllTimersAsync();+ const result = await enforcement;++ expect(runStoredPolicy.mock.calls.map(([id]) => id)).toEqual([+ "pdf",+ "image",+ "pdf",+ ]);+ expect(runStoredPolicy.mock.calls[1][1]).toEqual([image]);+ expect(runStoredPolicy.mock.calls[2][1][0].name).toBe("doc.pdf");+ expect(result.map((file) => file.name)).toEqual([+ "doc.pdf",+ "scan.pdf",+ "letter.docx",+ ]);+ expect(result[2]).toBe(word);+ });++ it("passes incompatible files through without dispatching", async () => {+ loadPolicies.mockReturnValue({+ image: exportPolicy({+ runsOnEditor: true,+ firstOperation: "/api/v1/convert/img/pdf",+ }),+ });+ const files = [pdf(), new File(["word"], "letter.docx")];++ expect(await enforceExportPolicies(files)).toBe(files);+ expect(runStoredPolicy).not.toHaveBeenCalled();+ });it("enforces an editor pipeline set to run on export", async () => {loadPolicies.mockReturnValue({@@ -71,9 +135,14 @@ describe("export-time policy selection", () => {}),} as unknown as PoliciesByKey);- await enforceExportPolicies([pdf()], ["file-1"]);+ const enforcement = enforceExportPolicies([pdf()], ["file-1"]);+ await vi.runAllTimersAsync();+ await enforcement;- expect(runStoredPolicy).toHaveBeenCalledWith("backend-editor");+ expect(runStoredPolicy).toHaveBeenCalledWith(+ "backend-editor",+ expect.anything(),+ );});it("leaves a swept pipeline alone, even though its source list is blank", async () => {@@ -85,7 +154,9 @@ describe("export-time policy selection", () => {}),} as unknown as PoliciesByKey);- await enforceExportPolicies([pdf()], ["file-1"]);+ const enforcement = enforceExportPolicies([pdf()], ["file-1"]);+ await vi.runAllTimersAsync();+ await enforcement;expect(runStoredPolicy).not.toHaveBeenCalled();});@@ -100,9 +171,14 @@ describe("export-time policy selection", () => {}),} as unknown as PoliciesByKey);- await enforceExportPolicies([pdf()], ["file-1"]);+ const enforcement = enforceExportPolicies([pdf()], ["file-1"]);+ await vi.runAllTimersAsync();+ await enforcement;- expect(runStoredPolicy).toHaveBeenCalledWith("backend-security");+ expect(runStoredPolicy).toHaveBeenCalledWith(+ "backend-security",+ expect.anything(),+ );});it("enforces in the team's run order, not object order", async () => {@@ -119,7 +195,9 @@ describe("export-time policy selection", () => {}),} as unknown as PoliciesByKey);- await enforceExportPolicies([pdf()], ["file-1"]);+ const enforcement = enforceExportPolicies([pdf()], ["file-1"]);+ await vi.runAllTimersAsync();+ await enforcement;expect(runStoredPolicy.mock.calls.map(([id]) => id)).toEqual(["backend-first",diff --git a/frontend/editor/src/proprietary/services/policyExport.ts b/frontend/editor/src/proprietary/services/policyExport.tsindex 4c1d54427b..b328fd438b 100644--- a/frontend/editor/src/proprietary/services/policyExport.ts+++ b/frontend/editor/src/proprietary/services/policyExport.ts@@ -7,11 +7,13 @@* Export is never hard-blocked: on failure the original file is exported and a* warning toast is shown. For "new version" policies, the run is also recorded* so the mounted import effect versions the in-editor file, not just the- * download. Only PDFs are enforced.+ * download. Each policy selects files using its first step's accepted inputs.*/import { loadPolicies } from "@app/services/policyStorage";import { loadPolicyCatalog } from "@app/services/policyCatalog";+import { policyAcceptsFile } from "@app/services/policyInput";+import { splitFileName } from "@app/utils/fileUtils";import {runStoredPolicy,getPolicyRun,@@ -19,6 +21,7 @@ import {resolvePolicyRunTarget,} from "@app/services/policyApi";import type { PolicyExecutionTarget } from "@app/services/policyPipeline";+import type { PolicyState } from "@app/types/policies";import {recordRunStart,isDispatched,@@ -38,10 +41,7 @@ const MAX_POLLS = 75;const TOAST_LINGER_MS = 10_000;const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));-const isPdf = (f: File) =>- f.type === "application/pdf" || /\.pdf$/i.test(f.name);--interface ExportPolicy {+interface ExportPolicy extends Pick<PolicyState, "firstOperation"> {policyKey: string;backendId: string;label: string;@@ -78,6 +78,7 @@ function activeExportPolicies(): ExportPolicy[] {.map(([id, s]) => ({policyKey: id,backendId: s.backendId as string,+ firstOperation: s.firstOperation,// A builder pipeline has no built-in category, so it labels by its own name.label: labels.get(id) ?? s.name ?? "Policy",outputMode: s.outputMode === "new_file" ? "new_file" : "new_version",@@ -106,9 +107,9 @@ async function runToCompletion(const out = view.outputs?.[0];if (!out) throw new Error("policy produced no output");const blob = await downloadPolicyOutput(out.fileId, target);- // Keep the export's filename; only the bytes are the enforced result.- const enforced = new File([blob], file.name, {- type: blob.type || file.type || "application/pdf",+ // Downstream policies must see the output's type, including its extension when MIME is absent.+ const enforced = new File([blob], out.fileName, {+ type: blob.type,});return { file: enforced, runId, target, outputs: view.outputs ?? [] };}@@ -139,10 +140,10 @@ function enforcedFilesSummary(names: string[]): string {}/**- * Enforce every active export-policy on each PDF just before export, returning+ * Enforce compatible active export policies just before export, returning* the files in order (enforced, or the original on failure). `fileIds[i]` is the* workspace id of `files[i]` when known — used to version the in-editor file for- * "new version" policies. Non-PDFs pass through untouched, and a single toast+ * "new version" policies. Incompatible files pass through untouched, and a single toast* (glowing in the policy's accent while it runs) fades a few seconds after the* result.*/@@ -152,8 +153,7 @@ export async function enforceExportPolicies(trigger: EnforcementTrigger = "export",): Promise<File[]> {const active = activeExportPolicies();- const targets = files.flatMap((f, i) => (isPdf(f) ? [i] : []));- if (!active.length || targets.length === 0) return files;+ if (!active.length || files.length === 0) return files;// Policies that haven't already enforced this exact file version. Enforcing// versions the in-editor file to the policy's output and marks that output@@ -162,7 +162,12 @@ export async function enforceExportPolicies(// new file id that isn't dispatched, so an edited file enforces afresh.const pendingFor = (fileId: string | undefined) =>active.filter((p) => !(fileId && isDispatched(p.policyKey, fileId)));- if (!targets.some((i) => pendingFor(fileIds?.[i]).length > 0)) return files;+ const hasCompatiblePolicy = (i: number) =>+ pendingFor(fileIds?.[i]).some((policy) =>+ policyAcceptsFile(policy, files[i]),+ );+ const targets = files.flatMap((_, i) => (hasCompatiblePolicy(i) ? [i] : []));+ if (targets.length === 0) return files;const names = active.map((p) => p.label).join(", ");@@ -172,9 +177,9 @@ export async function enforceExportPolicies(return runQueued({ label: names, trigger }, async () => {// An earlier queued job may have just enforced these same files and marked// them dispatched, so re-check at run time before doing (or announcing) work.- if (!targets.some((i) => pendingFor(fileIds?.[i]).length > 0)) return files;+ if (!targets.some(hasCompatiblePolicy)) return files;- const pending = targets.filter((i) => pendingFor(fileIds?.[i]).length > 0);+ const pending = targets.filter(hasCompatiblePolicy);const total = pending.length;const progressTitle = (done: number) =>total === 1@@ -208,13 +213,20 @@ export async function enforceExportPolicies(// file (recording every policy would double-consume the same input).let versionRun: (PolicyRunResult & { policyKey: string }) | undefined;for (const policy of toRun) {+ if (!policyAcceptsFile(policy, current)) continue;const result = await runToCompletion(policy.backendId, current);current = result.file;if (policy.outputMode === "new_version" && fileId) {versionRun = { ...result, policyKey: policy.policyKey };}}- out[i] = current;+ const [base, inputExtension] = splitFileName(file.name);+ const [, outputExtension] = splitFileName(current.name);+ out[i] = new File(+ [current],+ base + (outputExtension || inputExtension),+ { type: current.type },+ );done += 1;if (done < total)updateToast(toastId, {diff --git a/frontend/editor/src/proprietary/services/policyInput.test.ts b/frontend/editor/src/proprietary/services/policyInput.test.tsnew file mode 100644index 0000000000..55b5c2b1ab--- /dev/null+++ b/frontend/editor/src/proprietary/services/policyInput.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { policyAcceptsFile } from "@app/services/policyInput";+import type { PolicyState } from "@app/types/policies";++describe("policy input compatibility", () => {+ it.each<[PolicyState["firstOperation"], string, string, boolean]>([+ ["/api/v1/misc/compress-pdf", "report.PDF", "", true],+ ["/api/v1/misc/compress-pdf", "report", "application/pdf", true],+ ["/api/v1/misc/compress-pdf", "scan.png", "image/png", false],+ ["/api/v1/convert/img/pdf", "scan.PNG", "", true],+ ["/api/v1/convert/img/pdf", "scan.svg", "", true],+ ["/api/v1/convert/img/pdf", "report.pdf", "application/pdf", false],+ ["/api/v1/convert/markdown/pdf", "notes.md", "", true],+ ["/api/v1/convert/markdown/pdf", "notes.txt", "", false],+ ["/api/v1/convert/file/pdf", "anything.custom", "", true],+ [null, "report.pdf", "application/pdf", false],+ [undefined, "report.pdf", "application/pdf", false],+ ])("%s selects %s: %s → %s", (firstOperation, name, type, expected) => {+ expect(policyAcceptsFile({ firstOperation }, { name, type })).toBe(+ expected,+ );+ });+});diff --git a/frontend/editor/src/proprietary/services/policyInput.ts b/frontend/editor/src/proprietary/services/policyInput.tsnew file mode 100644index 0000000000..caabb8bd15--- /dev/null+++ b/frontend/editor/src/proprietary/services/policyInput.ts@@ -0,0 +1,15 @@+import type { StirlingFileStub } from "@app/types/fileContext";+import type { PolicyState } from "@app/types/policies";+import { toolIOFor } from "@app/types/toolIO";+import { toolAcceptsFile } from "@app/utils/toolIOCompat";++/** Automatic enforcement requires a known first step that accepts the current file. */+export function policyAcceptsFile(+ policy: Pick<PolicyState, "firstOperation"> | undefined,+ file: Pick<StirlingFileStub, "name" | "type" | "processedFile">,+): boolean {+ const operation = policy?.firstOperation;+ return Boolean(+ operation && toolIOFor(operation) && toolAcceptsFile(operation, file),+ );+}diff --git a/frontend/editor/src/proprietary/services/policyPipeline.test.ts b/frontend/editor/src/proprietary/services/policyPipeline.test.tsindex b07a21908c..f79310a3a2 100644--- a/frontend/editor/src/proprietary/services/policyPipeline.test.ts+++ b/frontend/editor/src/proprietary/services/policyPipeline.test.ts@@ -37,9 +37,22 @@ const backendPolicy: BackendPolicy = {};describe("fromBackendPolicy", () => {+ it("does not admit an unknown first endpoint for automatic enforcement", () => {+ const decoded = fromBackendPolicy({+ ...backendPolicy,+ steps: [+ { operation: "/unknown", parameters: {} },+ ...backendPolicy.steps,+ ],+ });++ expect(decoded.firstOperation).toBeNull();+ });+it("decodes a stored policy's output.options bag into frontend settings", () => {const decoded = fromBackendPolicy(backendPolicy);expect(decoded.id).toBe("p1");+ expect(decoded.firstOperation).toBe("/api/v1/misc/compress-pdf");expect(decoded.policyKey).toBe("security");expect(decoded.enabled).toBe(true);expect(decoded.sources).toEqual([]);diff --git a/frontend/editor/src/proprietary/services/policyPipeline.ts b/frontend/editor/src/proprietary/services/policyPipeline.tsindex b68d283973..c8399f7803 100644--- a/frontend/editor/src/proprietary/services/policyPipeline.ts+++ b/frontend/editor/src/proprietary/services/policyPipeline.ts@@ -14,9 +14,14 @@import { resolveRunOn, type PolicyRunOn } from "@app/policies/runOn";import type { AutomationConfig } from "@app/types/automation";import type { PolicyFolderSettings } from "@app/types/policies";+import {+ isToolEndpoint,+ type ToolEndpoint,+} from "@app/hooks/tools/shared/toolApiMapping";/** A single backend pipeline step: a tool endpoint path + its scalar params. */export interface BackendPipelineStep {+ /** Stored pipelines can contain endpoints this frontend version does not recognise. */operation: string;parameters: Record<string, unknown>;fileParameters?: Record<string, string>;@@ -105,6 +110,8 @@ export interface PolicyRunView {/** The decoded policy read back from the backend. */export interface DecodedPolicy {id: string;+ /** Validated first endpoint; null for an empty pipeline or an unrecognised first step. */+ firstOperation: ToolEndpoint | null;/** The policy this record belongs to, read from `output.options.categoryId`. */policyKey: string;name: string;@@ -144,8 +151,11 @@ export function fromBackendPolicy(policy: BackendPolicy): DecodedPolicy {const num = (v: unknown, fallback: number) =>typeof v === "number" ? v : fallback;const policyKey = str(meta.categoryId);+ const firstOperation = policy.steps[0]?.operation;return {id: policy.id,+ firstOperation:+ firstOperation && isToolEndpoint(firstOperation) ? firstOperation : null,policyKey,name: policy.name,enabled: policy.enabled,diff --git a/frontend/editor/src/proprietary/services/policyStorage.test.ts b/frontend/editor/src/proprietary/services/policyStorage.test.tsindex 3f7dd48c11..2110b8ae97 100644--- a/frontend/editor/src/proprietary/services/policyStorage.test.ts+++ b/frontend/editor/src/proprietary/services/policyStorage.test.ts@@ -28,6 +28,27 @@ describe("policyStorage", () => {expect(reloaded.retention.configured).toBe(false);});+ it.each(["security", "builder-pipeline"])(+ "validates cached input endpoints for %s without losing the unloaded state",+ (policyKey) => {+ for (const [stored, expected] of [+ ["/api/v1/misc/compress-pdf", "/api/v1/misc/compress-pdf"],+ ["/unknown", null],+ [null, null],+ [undefined, undefined],+ ]) {+ localStorage.setItem(+ "stirling-policies-state",+ JSON.stringify({+ [policyKey]: { configured: true, firstOperation: stored },+ }),+ );++ expect(loadPolicies()[policyKey].firstOperation).toBe(expected);+ }+ },+ );+it("merges partial field-value updates without clobbering siblings", () => {updatePolicy("security", { fieldValues: { detectPII: false } });updatePolicy("security", { reviewerEmail: "[email protected]" });diff --git a/frontend/editor/src/proprietary/services/policyStorage.ts b/frontend/editor/src/proprietary/services/policyStorage.tsindex 29d0d53320..f7a219a427 100644--- a/frontend/editor/src/proprietary/services/policyStorage.ts+++ b/frontend/editor/src/proprietary/services/policyStorage.ts@@ -8,6 +8,7 @@import { loadPolicyCatalog } from "@app/services/policyCatalog";import { defaultRunOn } from "@app/policies/runOn";import type { PoliciesByKey, PolicyState } from "@app/types/policies";+import { isToolEndpoint } from "@app/hooks/tools/shared/toolApiMapping";const STORAGE_KEY = "stirling-policies-state";@@ -92,6 +93,16 @@ export function loadPolicies(): PoliciesByKey {for (const [key, state] of Object.entries(parsed)) {if (!out[key] && state) out[key] = state as PolicyState;}+ // Cached endpoints can come from a different frontend version.+ for (const state of Object.values(out)) {+ const operation = state.firstOperation;+ if (+ operation !== undefined &&+ (typeof operation !== "string" || !isToolEndpoint(operation))+ ) {+ state.firstOperation = null;+ }+ }return out;}diff --git a/frontend/editor/src/proprietary/types/policies.ts b/frontend/editor/src/proprietary/types/policies.tsindex 2e74a924fa..9e8e404e4a 100644--- a/frontend/editor/src/proprietary/types/policies.ts+++ b/frontend/editor/src/proprietary/types/policies.ts@@ -9,6 +9,7 @@*/import type { ReactNode } from "react";+import type { ToolEndpoint } from "@app/types/toolApiTypes";/** Static definition of a policy category (the "what it does"). */export interface PolicyCategory {@@ -85,6 +86,8 @@ export interface PolicyState {* it has been persisted server-side; used to update/delete/run it.*/backendId?: string;+ /** First stored step's endpoint; absent before fetch, null for an empty or unknown first step. */+ firstOperation?: ToolEndpoint | null;/*** A built-in policy (one of the shipped catalog categories) rather than a* user-created one. Default policies are configurable but NOT deletable — the