#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
Keep editor files when delivering externally (#7987)
Anthony Stirlingcdad25b6ccc6
diff --git a/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java b/app/common/src/main/java/stirling/software/common/service/JobExecutorService.javaindex eca4413350..58211b1f70 100644--- a/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java+++ b/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java@@ -1,8 +1,11 @@package stirling.software.common.service;import java.io.IOException;+import java.util.Collections;+import java.util.IdentityHashMap;import java.util.List;import java.util.Map;+import java.util.Set;import java.util.UUID;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;@@ -218,6 +221,14 @@ public class JobExecutorService {return ResponseEntity.internalServerError().body(Map.of("error", "Job timed out after " + timeoutToUse + " ms"));} catch (RuntimeException e) {+ Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());+ for (Throwable nested = e;+ nested != null && seen.add(nested);+ nested = nested.getCause()) {+ if (nested instanceof org.springframework.web.ErrorResponseException response) {+ throw response;+ }+ }Throwable cause = e.getCause();if (e instanceof IllegalArgumentException|| causediff --git a/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java b/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.javaindex e3d6dd0c1d..d5a8ba3584 100644--- a/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java+++ b/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java@@ -3,6 +3,8 @@ package stirling.software.common.service;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertInstanceOf;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyLong;@@ -21,6 +23,8 @@ import java.util.function.Supplier;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.EnumSource;import org.mockito.ArgumentCaptor;import org.mockito.Captor;import org.mockito.Mock;@@ -141,6 +145,46 @@ class JobExecutorServiceTest {assertEquals("Job failed: Test error", errorMap.get("error"));}+ @ParameterizedTest+ @EnumSource(+ value = HttpStatus.class,+ names = {"UNPROCESSABLE_ENTITY", "NOT_IMPLEMENTED", "SERVICE_UNAVAILABLE"})+ void shouldPreserveHttpErrorsFromSyncJobs(HttpStatus status) {+ var error =+ new org.springframework.web.server.ResponseStatusException(+ status, "Cannot prepare document");+ assertSame(+ error,+ assertThrows(+ org.springframework.web.server.ResponseStatusException.class,+ () ->+ jobExecutorService.runJobGeneric(+ false,+ () -> {+ throw error;+ })));+ }++ @ParameterizedTest+ @EnumSource(+ value = HttpStatus.class,+ names = {"UNAUTHORIZED", "UNPROCESSABLE_ENTITY", "SERVICE_UNAVAILABLE"})+ void shouldPreserveWrappedHttpErrorsFromSyncJobs(HttpStatus status) {+ var error =+ new org.springframework.web.server.ResponseStatusException(+ status, "Cannot prepare document");+ assertSame(+ error,+ assertThrows(+ org.springframework.web.server.ResponseStatusException.class,+ () ->+ jobExecutorService.runJobGeneric(+ false,+ () -> {+ throw new RuntimeException(new RuntimeException(error));+ })));+ }+@Testvoid shouldQueueJobWhenResourcesLimited() throws Exception {// Givendiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.javaindex 39bac04ef7..5cad2d4ff2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java@@ -352,25 +352,20 @@ public class PolicyController {* nothing to check.*/private void requireAccessibleOutput(Policy policy) {- // An editor policy hands its results back to the workspace the file came from. A stored- // destination would send the run to a folder or bucket instead, leaving the editor's copy- // untouched - and the editor's import would then have nothing to collect.- if (policy.editor().allowed() && !policy.outputIds().isEmpty()) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST,- "An editor policy delivers back to the editor and can't also have a"- + " destination");- }// A routing rule's destination is checked on exactly the same terms as a plain output: it// must resolve, be accessible, and not be the editor.Stream.concat(policy.outputIds().stream(),policy.routingRules().stream().map(RoutingRule::outputId)).distinct()- .forEach(outputId -> requireAccessibleDestination(outputId, policy.steps()));+ .forEach(+ outputId ->+ requireAccessibleDestination(+ outputId, policy.steps(), policy.editor().allowed()));}- private void requireAccessibleDestination(String outputId, List<PipelineStep> steps) {+ private void requireAccessibleDestination(+ String outputId, List<PipelineStep> steps, boolean editorPolicy) {Source destination =sourceStore.get(outputId)@@ -381,6 +376,10 @@ public class PolicyController {HttpStatus.BAD_REQUEST,"Unknown or inaccessible output source: "+ outputId));+ if (editorPolicy && !destination.enabled()) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "The output destination is disabled");+ }if (EditorSource.TYPE.equals(destination.type())) {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The editor can't be used as an output destination");@@ -650,6 +649,12 @@ public class PolicyController {() ->new ResponseStatusException(HttpStatus.NOT_FOUND, "No policy: " + policyId));+ requireAccessibleOutput(policy);+ try {+ policyValidator.validateEditorOutput(policy);+ } catch (IllegalArgumentException e) {+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());+ }stampPolicyAudit(policy.toDefinition());PolicyInputs inputs = toInputs(files);String runId =diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.javaindex ce42dd6cf3..59ba7f79d5 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java@@ -324,6 +324,7 @@ public class PolicyEngine {}PolicyRun run =new PolicyRun(runId, policyId, definition, sourceId, fileIdentity, triggeringUser);+ taskManager.putMetadata(runId, "externalOutput", String.valueOf(run.externalOutput()));registry.register(run);return run;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.javaindex af912a62a0..3bdee317e5 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java@@ -94,6 +94,13 @@ public class PolicyRun {this.triggeringUser = triggeringUser;}+ /** True when results are sent elsewhere and must not replace the editor's input. */+ public boolean externalOutput() {+ return definition.outputs().stream().anyMatch(output -> !"inline".equals(output.type()))+ || definition.routing().stream()+ .anyMatch(route -> !"inline".equals(route.destination().type()));+ }+public int stepCount() {return definition.steps().size();}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.javaindex 16b7b58275..13265acd5b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRunView.java@@ -27,7 +27,8 @@ public record PolicyRunView(* live runs needs something to call them before any output exists. Null for uploads and* cross-node views, whose identity is not name-shaped.*/- String fileName) {+ String fileName,+ boolean externalOutput) {public static PolicyRunView of(PolicyRun run) {return new PolicyRunView(@@ -41,7 +42,8 @@ public record PolicyRunView(run.getErrorSubscribed(),run.getOutputs(),run.getCreatedAt().toEpochMilli(),- fileNameOf(run.getFileIdentity()));+ fileNameOf(run.getFileIdentity()),+ run.externalOutput());}/**@@ -84,6 +86,7 @@ public record PolicyRunView(null,outputs,createdAt,- null);+ null,+ Boolean.parseBoolean(meta.get("externalOutput")));}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.javaindex 67f46593a1..bb2d8b3c9d 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java@@ -64,6 +64,7 @@ import stirling.software.proprietary.policy.model.PolicyRun;import stirling.software.proprietary.policy.model.PolicyRunView;import stirling.software.proprietary.policy.progress.PolicyProgressListener;import stirling.software.proprietary.policy.source.EditorSource;+import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.policy.source.SourceAccessGuard;import stirling.software.proprietary.policy.source.SourceDocCounter;import stirling.software.proprietary.policy.source.SourceStore;@@ -898,6 +899,26 @@ class PolicyControllerTest {return reference.getValue();}+ @Test+ void rejectsLegacyEditorCorpusExportsBeforeStartingARun() {+ Policy p = policy("a", 1L);+ when(policyStore.get("a")).thenReturn(Optional.of(p));+ when(policyAccessGuard.canAccess(p)).thenReturn(true);+ doThrow(new IllegalArgumentException("Editor policies must return PDFs"))+ .when(policyValidator)+ .validateEditorOutput(p);++ assertThatThrownBy(() -> controller.runStoredPolicy("a", new PolicyRunFiles()))+ .isInstanceOfSatisfying(+ ResponseStatusException.class,+ error -> {+ assertThat(error.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);+ assertThat(error.getReason())+ .contains("Editor policies must return PDFs");+ });+ verify(policyRunner, never()).runWith(any(), any(), any(), any());+ }+@Test@DisplayName("runs a stored, accessible policy")void runsStored() throws Exception {@@ -931,6 +952,31 @@ class PolicyControllerTest {assertThat(documentReferenceOf(filesWith("editor-file-1", 3))).isNull();}+ @Test+ void refusesAnInaccessibleDestinationBeforeSubmittingTheEditorCopy() {+ Policy p = policy("a", 1L).withOutputIds(List.of("other-team"));+ Source destination =+ new Source(+ "other-team",+ "Private",+ "folder",+ Map.of("directory", "/out"),+ true,+ "owner",+ 2L);+ when(policyStore.get("a")).thenReturn(Optional.of(p));+ when(policyAccessGuard.canAccess(p)).thenReturn(true);+ when(sourceStore.get("other-team")).thenReturn(Optional.of(destination));+ when(sourceAccessGuard.canAccess(destination)).thenReturn(false);+ assertThatThrownBy(() -> controller.runStoredPolicy("a", new PolicyRunFiles()))+ .isInstanceOf(ResponseStatusException.class)+ .satisfies(+ e ->+ assertThat(((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.BAD_REQUEST));+ verifyNoInteractions(policyRunner);+ }+@Test@DisplayName("keeps the reference when the one document sent was empty")void keepsTheReferenceForAnEmptyUpload() throws Exception {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.javaindex 2db5871964..bce2eb1654 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java@@ -19,6 +19,65 @@ class PolicyRunTest {"run-1", "p1", new PipelineDefinition("t", List.of(), List.of()), null, null, null);}+ @Test+ void externalDeliveryIsCapturedInTheRunView() {+ PolicyRun run =+ new PolicyRun(+ "run",+ "policy",+ new PipelineDefinition(+ "copy", List.of(), List.of(OutputSpec.folder("/out"))),+ null,+ null,+ null);+ assertTrue(PolicyRunView.of(run).externalOutput());+ assertFalse(PolicyRunView.of(run()).externalOutput());+ }++ @Test+ void routedExternalDeliveryIsCapturedEvenWithAnInlineFallback() {+ var condition =+ new stirling.software.proprietary.document.conditions.Condition.MatchesAny(+ new stirling.software.proprietary.document.conditions.ConditionInput+ .DocumentField("document.extension"),+ List.of("pdf"));+ for (OutputSpec destination : List.of(OutputSpec.inline(), OutputSpec.folder("/out"))) {+ PolicyRun routed =+ new PolicyRun(+ "run",+ "policy",+ new PipelineDefinition(+ "route",+ List.of(),+ List.of(OutputSpec.inline()),+ List.of(+ new RoutedDestination(+ new RoutingRule(condition, "destination"),+ destination))),+ null,+ null,+ null);+ assertEquals(+ !"inline".equals(destination.type()),+ PolicyRunView.of(routed).externalOutput());+ }+ }++ @Test+ void sharedJobProjectionPreservesExternalDelivery() {+ var entry =+ new stirling.software.common.cluster.JobStoreEntry(+ "run",+ stirling.software.common.cluster.JobStoreEntry.JobState.COMPLETE,+ "node-a",+ java.time.Instant.now(),+ null,+ null,+ List.of("receipt"),+ java.util.Map.of("policyId", "policy", "externalOutput", "true"));+ assertTrue(PolicyRunView.ofEntry(entry).externalOutput());+ }+@Testvoid aCancelledRunCannotStart() {PolicyRun run = run();diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 1453aae5f4..33d3ac5edd 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -8982,7 +8982,6 @@ chooseSource = "Choose a source"discard = "Discard changes"editorDestination = "Editor"editorDestinationDetail = "Replaces the file you ran it on"-editorDestinationHelp = "This pipeline runs on the files in your workspace, and its results replace the file it ran on. There is nowhere else to send them."inputs = "Input"inputSource = "Input source"inputTrigger = "Trigger"@@ -9039,7 +9038,7 @@ label = "Change icon"chunkSize = "Chunk size"chunkSizeHint = "Characters per chunk. Smaller chunks retrieve more precisely; larger ones keep more context together."destinationNeedsChunks = "This vector database destination needs a final AI ingestion step that exports chunks only."-editorPdfOnly = "Editor policies return PDFs only. To export chunks or Markdown, choose a saved input source and a file destination."+editorPdfOnly = "Only PDFs can return to the editor. To export chunks or Markdown, choose Keep originals and send to a destination under Output."exportChunks = "Export chunks as JSONL"exportChunksHint = "One chunk per line with its page span, ready to load into another system."exportMarkdown = "Export markdown"@@ -9586,6 +9585,13 @@ labelsHeading = "Classification labels"noTools = "Enable at least one action."saveFailed = "Couldn't save the pipeline. Please try again."+[portal.policies.wizard.locations]+delivery = "Delivery"+editorOutput = "Processed PDFs return to the editor workspace."+keepOriginal = "Keep originals and send to a destination"+keepOriginalHelp = "A copy runs in the background. Your editor files stay unchanged; results are saved to the destination below."+returnToEditor = "Return results to editor"+[portal.policies.wizard.routing]chooseDestination = "Choose a destination"chooseSource = "Choose what to watch"diff --git a/frontend/editor/src/portal/components/pipelines/EditorDeliverySelect.tsx b/frontend/editor/src/portal/components/pipelines/EditorDeliverySelect.tsxnew file mode 100644index 0000000000..85faaa76cd--- /dev/null+++ b/frontend/editor/src/portal/components/pipelines/EditorDeliverySelect.tsx@@ -0,0 +1,59 @@+import { useTranslation } from "react-i18next";+import { FormField, Select } from "@app/ui";++interface Props {+ external: boolean;+ requiresDestination: boolean;+ onChange: (external: boolean) => void;+}++/** Editor delivery must be explicit before choosing a saved destination. */+export function EditorDeliverySelect({+ external,+ requiresDestination,+ onChange,+}: Props) {+ const { t } = useTranslation();+ return (+ <FormField+ label={t("portal.policies.wizard.locations.delivery", "Delivery")}+ helperText={+ external+ ? t(+ "portal.policies.wizard.locations.keepOriginalHelp",+ "A copy runs in the background. Your editor files stay unchanged; results are saved to the destination below.",+ )+ : t(+ "portal.policies.wizard.locations.editorOutput",+ "Processed PDFs return to the editor workspace.",+ )+ }+ >+ <Select+ inputSize="sm"+ value={external ? "destination" : "workspace"}+ onChange={(value) => value && onChange(value === "destination")}+ options={[+ ...(!requiresDestination+ ? [+ {+ value: "workspace",+ label: t(+ "portal.policies.wizard.locations.returnToEditor",+ "Return results to editor",+ ),+ },+ ]+ : []),+ {+ value: "destination",+ label: t(+ "portal.policies.wizard.locations.keepOriginal",+ "Keep originals and send to a destination",+ ),+ },+ ]}+ />+ </FormField>+ );+}diff --git a/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsxindex 9cb0eb5419..32f546dd0e 100644--- a/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx+++ b/frontend/editor/src/portal/components/pipelines/IngestStepConfig.tsx@@ -47,10 +47,7 @@ export function IngestStepConfig({{editorInput && (<Bannertone="info"- description={t(- "portal.pipelines.builder.ingest.editorPdfOnly",- "Editor policies return PDFs only. To export chunks or Markdown, choose a saved input source and a file destination.",- )}+ description={t("portal.pipelines.builder.ingest.editorPdfOnly")}/>)}{(!editorInput || !includeOriginal) && (diff --git a/frontend/editor/src/portal/components/pipelines/docparseStep.ts b/frontend/editor/src/portal/components/pipelines/docparseStep.tsindex ea51aa0815..e391675b33 100644--- a/frontend/editor/src/portal/components/pipelines/docparseStep.ts+++ b/frontend/editor/src/portal/components/pipelines/docparseStep.ts@@ -38,13 +38,7 @@ export function ingestStepConfigured(): boolean {if (!isIngestStep(step)) return true;const params = step.params as IngestStepParams;- if (- editorInput &&- (params.exportChunksJsonl === true ||- params.exportMarkdown === true ||- params.includeOriginal === false)- )- return false;+ if (editorInput && ingestRequiresExternalDelivery(params)) return false;const doesSomething =params.index !== false ||params.exportMarkdown === true ||@@ -89,3 +83,19 @@ export function prepareVectorDestination(},];}+/** Corpus exports need a saved destination when the editor supplies the input. */+export function needsCorpusDestination(steps: WorkingToolStep[]): boolean {+ return steps.some((step) => {+ if (!isIngestStep(step)) return false;+ const params = step.params as IngestStepParams;+ return ingestRequiresExternalDelivery(params);+ });+}++function ingestRequiresExternalDelivery(params: IngestStepParams): boolean {+ return (+ params.exportChunksJsonl === true ||+ params.exportMarkdown === true ||+ params.includeOriginal === false+ );+}diff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsxindex 92358b20cb..ad71473627 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx@@ -108,6 +108,9 @@ vi.mock("@portal/components/pipelines/DestinationPicker", () => ({<button type="button" onClick={() => onEdit(value[0] ?? "")}>edit destination</button>+ <button type="button" onClick={() => onChange([])}>+ clear destination+ </button></>),}));@@ -899,6 +902,105 @@ describe("PipelineBuilder", () => {expect(body.outputIds).toEqual([]);});+ it("keeps external delivery selected when a saved destination is cleared", async () => {+ fetchSources.mockResolvedValue({+ kpis: [],+ sources: [SOURCE, EDITOR_SOURCE],+ });+ fetchPipeline.mockResolvedValue({+ ...POLICY,+ inputs: [],+ editor: { allowed: true, runOn: "upload" },+ outputIds: ["src-in"],+ routingRules: [],+ });+ renderBuilder("/processor/pipelines/plc-1");+ await screen.findByLabelText("portal.pipelines.builder.rename");+ await openOutput();+ fireEvent.click(await screen.findByText("clear destination"));+ expect(+ screen.getByRole("textbox", {+ name: "portal.policies.wizard.locations.delivery",+ }),+ ).toHaveValue("portal.policies.wizard.locations.keepOriginal");+ expect(screen.getByText("pick output")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "portal.pipelines.composer.save" }),+ ).toBeDisabled();+ });++ it("clears hidden routing blockers when returning results to the editor", async () => {+ HTMLElement.prototype.scrollIntoView = vi.fn();+ fetchSources.mockResolvedValue({+ kpis: [],+ sources: [SOURCE, EDITOR_SOURCE],+ });+ fetchPipeline.mockResolvedValue({+ ...POLICY,+ inputs: [],+ editor: { allowed: true, runOn: "upload" },+ outputIds: ["src-in"],+ routingRules: [routingRule([])],+ });+ renderBuilder("/processor/pipelines/plc-1");+ await screen.findByLabelText("portal.pipelines.builder.rename");+ await openOutput();+ fireEvent.click(+ screen.getByRole("textbox", {+ name: "portal.policies.wizard.locations.delivery",+ }),+ );+ fireEvent.click(+ await screen.findByText(+ "portal.policies.wizard.locations.returnToEditor",+ ),+ );+ fireEvent.click(screen.getByText("portal.pipelines.composer.save"));+ await waitFor(() => expect(savePipeline).toHaveBeenCalledTimes(1));+ expect(savePipeline.mock.calls[0][0]).toMatchObject({+ outputIds: [],+ routingRules: [],+ });+ });++ it("saves a separate destination for an editor copy", async () => {+ HTMLElement.prototype.scrollIntoView = vi.fn();+ fetchSources.mockResolvedValue({+ kpis: [],+ sources: [SOURCE, EDITOR_SOURCE],+ });+ renderBuilder("/processor/pipelines/new");+ fireEvent.change(+ await screen.findByLabelText("portal.pipelines.composer.name"),+ { target: { value: "Copy to archive" } },+ );+ await addTool("Compress");+ await pickInputSource("Editor");+ await openOutput();+ fireEvent.click(+ await screen.findByRole("textbox", {+ name: "portal.policies.wizard.locations.delivery",+ }),+ );+ fireEvent.click(+ await screen.findByText("portal.policies.wizard.locations.keepOriginal"),+ );+ expect(+ screen.getByRole("button", {+ name: "portal.pipelines.composer.create",+ }),+ ).toBeDisabled();+ fireEvent.click(await screen.findByText("pick output"));+ fireEvent.click(screen.getByText("portal.pipelines.composer.create"));+ await waitFor(() => expect(savePipeline).toHaveBeenCalledTimes(1));+ expect(savePipeline.mock.calls[0][0]).toMatchObject({+ editor: { allowed: true, runOn: "upload" },+ required: false,+ inputs: [],+ outputIds: ["src-in"],+ });+ });+it("blocks a vector route with a file fallback until chunks are prepared", async () => {fetchSources.mockResolvedValue({kpis: [],diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsxindex 176aa97c0e..44a9055b2a 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx@@ -1,11 +1,6 @@+import { EditorDeliverySelect } from "@portal/components/pipelines/EditorDeliverySelect";import { requiresClassification } from "@app/data/classificationConditions";import { isConditionComplete } from "@app/conditions/validation";-import {- isIngestStep,- ingestStepConfigured,- vectorDestinationConfigured,- prepareVectorDestination,-} from "@portal/components/pipelines/docparseStep";import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useLocation, useNavigate, useParams } from "react-router-dom";import { useTranslation } from "react-i18next";@@ -116,6 +111,13 @@ import {newIntegrationStep,stepOperation,} from "@portal/components/pipelines/integrationStep";+import {+ isIngestStep,+ ingestStepConfigured,+ needsCorpusDestination,+ vectorDestinationConfigured,+ prepareVectorDestination,+} from "@portal/components/pipelines/docparseStep";import {MANUAL,MANUAL_OPTION,@@ -323,6 +325,12 @@ export function PipelineBuilder() {const [outputOptions, setOutputOptions] = useState<Record<string, unknown>>({},);+ const [destinationRequested, setDestinationRequested] = useState(false);+ const requiresDestination = needsCorpusDestination(steps);+ const externalEditorOutput =+ isEditorInput &&+ (requiresDestination || outputIds.length > 0 || destinationRequested);+ const returnsToEditor = isEditorInput && !externalEditorOutput;const [outputType, setOutputType] = useState("inline");/*** Whether the user has asked for each end of the chain yet, distinguishing "not offered" from@@ -424,8 +432,13 @@ export function PipelineBuilder() {setSteps((policy?.steps ?? []).map((step) => deserializeToolStep(step, allTools)),);- setOutputIds(seedsEditor ? [] : (policy?.outputIds ?? []));- setRoutingRules(seedsEditor ? [] : (policy?.routingRules ?? []));+ setOutputIds(policy?.outputIds ?? []);+ setRoutingRules(policy?.routingRules ?? []);+ setDestinationRequested(+ seedsEditor &&+ ((policy?.outputIds?.length ?? 0) > 0 ||+ (policy?.routingRules?.length ?? 0) > 0),+ );setSeeded(true);}, [isEdit,@@ -495,11 +508,6 @@ export function PipelineBuilder() {triggerType: keepTrigger ? current.triggerType : MANUAL,};});- // The editor hands results back to the workspace, so it has no destination to choose.- if (type === EDITOR_SOURCE_TYPE) {- setOutputIds([]);- setOutputAsked(false);- }}/** Put an end on the chain and open it, so the click that asks for it also offers the choice. */@@ -636,7 +644,7 @@ export function PipelineBuilder() {.filter((step) =>!integrationStepConfigured(step) ||- !ingestStepConfigured(step, isEditorInput) ||+ !ingestStepConfigured(step, returnsToEditor) ||stepNeedsConfiguring(step, allTools),).map(stepLabel);@@ -787,7 +795,7 @@ export function PipelineBuilder() {writableSources.some((source) => source.id === outputIds[0] && source.status !== "disabled",);- const outputValid = isEditorInput || (destinationReady && vectorReady);+ const outputValid = returnsToEditor || (destinationReady && vectorReady);const classifies = steps.some(isClassifyStep);// Mirrors PolicyValidator.validateRoutingRules: a rule with nothing to match on, or nowhere to// send, would be rejected on save - so it is named here rather than surfaced as a server error.@@ -809,7 +817,7 @@ export function PipelineBuilder() {blockers.push(t("portal.pipelines.builder.blocker.source"));else if (!scheduleValid)blockers.push(t("portal.pipelines.builder.blocker.schedule"));- if (!isEditorInput && !destinationReady)+ if (!returnsToEditor && !destinationReady)blockers.push(t("portal.pipelines.builder.blocker.destination"));if (!vectorReady)blockers.push(t("portal.pipelines.builder.ingest.destinationNeedsChunks"));@@ -934,7 +942,7 @@ export function PipelineBuilder() {enabled: enabledOverride ?? enabled,// Blocking is only meaningful for an editor pipeline; a source-backed one is never a policy,// so don't persist a stale flag if the source was switched away from the editor.- required: isEditorInput && required,+ required: returnsToEditor && required,icon,// The editor is virtual - there is no stored Source to pull from, and nothing server-side// sweeps it - so it is never a wire input; its participation is recorded on `editor` below.@@ -948,8 +956,8 @@ export function PipelineBuilder() {editor: { allowed: isEditorInput, runOn },// An editor pipeline delivers back into the workspace. A stored destination would send the// run to a folder or bucket instead, leaving the editor's copy untouched.- outputIds: isEditorInput ? [] : outputIds,- routingRules: isEditorInput ? [] : routingRules,+ outputIds: returnsToEditor ? [] : outputIds,+ routingRules: returnsToEditor ? [] : routingRules,};await savePipeline(policy);await invalidatePipelines();@@ -1221,7 +1229,9 @@ export function PipelineBuilder() {// than the ungrammatical, untranslatable "Run every 1 hours".return t(`portal.pipelines.composer.runsEvery.${input.scheduleUnit.toLowerCase()}`,- { count: Number(input.scheduleCount) || 1 },+ {+ count: Number(input.scheduleCount) || 1,+ },);return t(`portal.pipelines.trigger.${input.triggerType}`, {defaultValue: input.triggerType,@@ -1367,43 +1377,49 @@ export function PipelineBuilder() {);}- if (selected === "output" && isEditorInput) {- return (- <p className="portal-builder__muted">- {t(- "portal.pipelines.builder.editorDestinationHelp",- "This pipeline runs on the files in your workspace, and its results replace the file it ran on. There is nowhere else to send them.",- )}- </p>- );- }-if (selected === "output") {return (<>- <RoutingSection- rules={routingRules}- onChange={setRoutingRules}- destinations={writableSources}- onCreateDestination={() => createSourceFor("output")}- canClassify={classifies}- aiClassificationEnabled={aiClassificationEnabled}- />- <DestinationPicker- label={- routingRules.length > 0- ? t(- "portal.pipelines.builder.routing.fallback",- "Everything else goes to",- )- : undefined- }- sources={writableSources}- value={outputIds}- onChange={setOutputIds}- onCreateNew={() => createSourceFor("output")}- onEdit={(sourceId) => setSourceModal({ open: true, sourceId })}- />+ {isEditorInput && (+ <EditorDeliverySelect+ external={externalEditorOutput}+ requiresDestination={requiresDestination}+ onChange={(external) => {+ setDestinationRequested(external);+ if (!external) {+ setOutputIds([]);+ setRoutingRules([]);+ }+ }}+ />+ )}+ {!returnsToEditor && (+ <>+ <RoutingSection+ rules={routingRules}+ onChange={setRoutingRules}+ destinations={writableSources}+ onCreateDestination={() => createSourceFor("output")}+ canClassify={classifies}+ aiClassificationEnabled={aiClassificationEnabled}+ />+ <DestinationPicker+ label={+ routingRules.length > 0+ ? t(+ "portal.pipelines.builder.routing.fallback",+ "Everything else goes to",+ )+ : undefined+ }+ sources={writableSources}+ value={outputIds}+ onChange={setOutputIds}+ onCreateNew={() => createSourceFor("output")}+ onEdit={(sourceId) => setSourceModal({ open: true, sourceId })}+ />+ </>+ )}{vectorOutput && !vectorReady && (<><p className="portal-builder__muted">@@ -1424,7 +1440,7 @@ export function PipelineBuilder() {if (selectedStep) {return (<PipelineStepSettings- editorInput={isEditorInput}+ editorInput={returnsToEditor}step={selectedStep}registry={allTools}onChange={(params) => updateStepParams(chosenSteps[0], params)}@@ -1447,7 +1463,7 @@ export function PipelineBuilder() {onIconChange={setIcon}required={required}onRequiredChange={setRequired}- runsOnEditor={isEditorInput}+ runsOnEditor={returnsToEditor}canManagePolicies={canManagePolicies}permissionsLoading={permissionsLoading}enabled={enabled}@@ -1472,7 +1488,7 @@ export function PipelineBuilder() {onIconChange={setIcon}required={required}onRequiredChange={setRequired}- runsOnEditor={isEditorInput}+ runsOnEditor={returnsToEditor}canManagePolicies={canManagePolicies}permissionsLoading={permissionsLoading}canSave={canSave}@@ -1533,7 +1549,7 @@ export function PipelineBuilder() {: null}output={- isEditorInput+ returnsToEditor? {label: t("portal.pipelines.builder.editorDestination",@@ -1543,9 +1559,9 @@ export function PipelineBuilder() {"portal.pipelines.builder.editorDestinationDetail","Replaces the file you ran it on",),- fixed: true,+ fixed: false,}- : outputAsked || outputValid+ : isEditorInput || outputAsked || outputValid? {label:chosenDestination?.name ??@@ -1560,7 +1576,11 @@ export function PipelineBuilder() {: undefined,warning: outputValid? undefined- : t("portal.pipelines.builder.needsDestination"),+ : chosenDestination && !vectorReady+ ? t(+ "portal.pipelines.builder.ingest.destinationNeedsChunks",+ )+ : t("portal.pipelines.builder.needsDestination"),}: null}diff --git a/frontend/editor/src/proprietary/components/policies/policyRunStore.ts b/frontend/editor/src/proprietary/components/policies/policyRunStore.tsindex 5092e97b53..ebf253388e 100644--- a/frontend/editor/src/proprietary/components/policies/policyRunStore.ts+++ b/frontend/editor/src/proprietary/components/policies/policyRunStore.ts@@ -30,7 +30,9 @@ export interface PolicyRunRecord {stepCount?: number;/** Output files (downloadable via /api/v1/general/files/{id}) once done. */outputs: { fileId: string; fileName: string }[];- /** True once ALL outputs have been imported into the workspace. */+ /** Snapshotted by the server: external results must never enter the workspace. */+ externalOutput?: boolean;+ /** True once delivery has been handled. */imported?: boolean;/** Output fileIds already imported — tracked per-file so a partial failure* retries only the missing ones and never re-adds the ones that succeeded. */diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsxindex 4064305a0b..5a0672da00 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.import.test.tsx@@ -119,6 +119,26 @@ beforeEach(() => {});describe("auto-run import: new-version output delivery", () => {+ it.each(["doc.chunks.jsonl", "indexing-report.json", "processed.pdf"])(+ "never imports external %s, even if the policy now replaces editor files",+ async (fileName) => {+ mocks.fileStubs = [{ id: "file-1" }];+ recordCompletedRun();+ updateRun("run-1", {+ externalOutput: true,+ outputs: [{ fileId: "out-1", fileName }],+ });+ await runImport();+ expect(getRun("run-1")?.outputFileIds).toEqual(["file-1"]);+ expect(mocks.downloadPolicyOutput).not.toHaveBeenCalled();+ expect(mocks.consumeFiles).not.toHaveBeenCalled();+ expect(mocks.addFiles).not.toHaveBeenCalled();+ expect(mocks.persistVersionedOutputs).not.toHaveBeenCalled();+ expect(mocks.updateFileMetadata).not.toHaveBeenCalled();+ expect(mocks.bumpRevision).not.toHaveBeenCalled();+ },+ );+it("preserves a converted output's extension for subsequent policies", async () => {recordCompletedRun();updateRun("run-1", {diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.tsindex 907f9bfa9b..8c4f2a548a 100644--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts@@ -211,6 +211,8 @@ export function usePolicyAutoRun(): void {backendId,rec.fileId as DispatchableFileId,rec.fileName,+ false,+ rec.externalOutput,);},QUEUE_RETRY_BASE_MS * 2 ** attempts,@@ -242,15 +244,25 @@ export function usePolicyAutoRun(): void {[scheduleQueueRetry],);- // 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.+ // Fire only the first compatible rewriting policy per file; the chaining+ // effect below runs the rest on each previous output. Background deliveries+ // independently receive the original upload.useEffect(() => {- // An older cache has no input metadata; wait for reconciliation to preserve the team's order.- if (- orderedUploadPolicyKeys.some(- (key) => policies[key].firstOperation === undefined,+ const backgroundPolicyKeys = Object.entries(policies)+ .filter(+ ([, policy]) =>+ policy.configured &&+ policy.enabled &&+ policy.runsOnEditor &&+ policy.externalOutput &&+ (policy.runOn ?? "upload") === "upload",)- )+ .map(([key]) => key);+ const candidateKeys = [+ ...new Set([...orderedUploadPolicyKeys, ...backgroundPolicyKeys]),+ ];+ // An older cache has no input metadata; wait for reconciliation to preserve the team's order.+ if (candidateKeys.some((key) => policies[key].firstOperation === undefined))return;for (const stub of fileStubs) {// Input-mode policies cover uploads only; tool-produced files are left to@@ -266,23 +278,38 @@ export function usePolicyAutoRun(): void {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 (- isDispatched(firstPolicyKey, stub.id) ||- dispatching.current.has(key)- ) {- continue;+ const keys = [+ ...new Set(+ [+ firstPolicyKey,+ ...backgroundPolicyKeys.filter((key) =>+ policyAcceptsFile(policies[key], stub),+ ),+ ].filter((key): key is string => Boolean(key)),+ ),+ ];+ for (const policyKey of keys) {+ const policy = policies[policyKey];+ if (!policy?.backendId) continue;+ const key = dispatchKey(policyKey, stub.id);+ // Skip if already run (persisted) or in flight - the in-memory guard covers the async wait.+ if (isDispatched(policyKey, stub.id) || dispatching.current.has(key)) {+ continue;+ }+ dispatching.current.add(key);+ void runPolicyOnFile(+ policyKey,+ policy.backendId,+ target,+ stub.name,+ false,+ policy.externalOutput,+ )+ .catch(() => {+ // Backstop: runPolicyOnFile handles its own failures.+ })+ .finally(() => dispatching.current.delete(key));}- dispatching.current.add(key);- void runPolicyOnFile(firstPolicyKey, backendId, target, stub.name)- .catch(() => {- // Backstop: runPolicyOnFile handles its own failures.- })- .finally(() => dispatching.current.delete(key));}}, [fileStubs, policies, orderedUploadPolicyKeys, unlocksVersion]);@@ -290,7 +317,8 @@ export function usePolicyAutoRun(): void {// run. isDispatched guards re-dispatch across reloads.useEffect(() => {for (const run of runs) {- if (run.status !== "COMPLETED" || !run.imported) continue;+ if (run.status !== "COMPLETED" || !run.imported || run.externalOutput)+ continue;if (chained.current.has(run.runId)) continue;const index = orderedUploadPolicyKeys.indexOf(run.policyKey);const remainingKeys =@@ -343,6 +371,13 @@ export function usePolicyAutoRun(): void {) {continue;}+ if (run.externalOutput) {+ updateRun(run.runId, {+ imported: true,+ outputFileIds: run.fileId ? [run.fileId] : [],+ });+ continue;+ }if (finishedWithNothingToDeliver(run)) {updateRun(run.runId, { imported: true });continue;@@ -490,6 +525,9 @@ async function reconcileServerRuns(policies: PoliciesByKey): Promise<void> {updateRun(view.runId, {status: view.status,outputs: view.outputs,+ ...(view.externalOutput === undefined+ ? {}+ : { externalOutput: view.externalOutput }),error: view.error,});// No-ops if already tracked, so this only adopts runs we'd otherwise have lost.@@ -506,6 +544,9 @@ async function reconcileServerRuns(policies: PoliciesByKey): Promise<void> {target: "saas",status: view.status,outputs: view.outputs,+ ...(view.externalOutput === undefined+ ? {}+ : { externalOutput: view.externalOutput }),error: view.error,// Adopted for feed visibility ONLY, never delivery: else a completed run evicted from the capped store gets re-adopted every refresh and re-delivered as a new file (no fileId → no parent), opening phantom duplicates forever. Client-recorded runs (real fileId) still deliver.imported: true,@@ -921,6 +962,9 @@ export async function poll(currentStep: view.currentStep,stepCount: view.stepCount,outputs: view.outputs,+ ...(view.externalOutput === undefined+ ? {}+ : { externalOutput: view.externalOutput }),error: view.error,errorCode: view.errorCode ?? null,});diff --git a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx b/frontend/editor/src/proprietary/components/viewer/Viewer.tsxindex 1862911eca..414c13b018 100644--- a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx+++ b/frontend/editor/src/proprietary/components/viewer/Viewer.tsx@@ -32,6 +32,7 @@ const Viewer = (props: ViewerProps & SignatureOverlayPassThrough) => {r.fileId === activeFileId &&// Classification runs async and must never block the viewer.!isClassificationPolicy(r.policyKey) &&+ !r.externalOutput &&(POLICY_IN_FLIGHT_STATUSES.includes(r.status) || r.retrying === true),): [];diff --git a/frontend/editor/src/proprietary/data/classificationPolicy.test.ts b/frontend/editor/src/proprietary/data/classificationPolicy.test.tsindex 65479052a7..0b4dcb9d51 100644--- a/frontend/editor/src/proprietary/data/classificationPolicy.test.ts+++ b/frontend/editor/src/proprietary/data/classificationPolicy.test.ts@@ -58,6 +58,7 @@ describe("orderedRewritingPolicies", () => {const mixed = {security: rewriter(0),inactive: { ...rewriter(1), enabled: false },+ background: { ...rewriter(6), externalOutput: true },notEditor: { ...rewriter(2), runsOnEditor: false },onExport: { ...rewriter(3), runOn: "export" },unconfigured: { ...rewriter(4), configured: false },diff --git a/frontend/editor/src/proprietary/data/classificationPolicy.ts b/frontend/editor/src/proprietary/data/classificationPolicy.tsindex 2ac4544141..4062f5d29e 100644--- a/frontend/editor/src/proprietary/data/classificationPolicy.ts+++ b/frontend/editor/src/proprietary/data/classificationPolicy.ts@@ -55,7 +55,9 @@ export function orderedRewritingPolicies(policies: PoliciesByKey): string[] {return Object.entries(policies).filter(([id, s]) =>- editorTriggerOf(s) === "upload" && policyDeliversOutputFiles(id),+ editorTriggerOf(s) === "upload" &&+ !s.externalOutput &&+ policyDeliversOutputFiles(id),).sort(([, a], [, b]) => (a.order ?? 0) - (b.order ?? 0)).map(([id]) => id);diff --git a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.tsindex 00dbea669c..51863ef2c4 100644--- a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts+++ b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts@@ -116,6 +116,16 @@ describe("buildPolicyBadgeMap — badge follows the document onto derived files"});});+it("shows external delivery as background activity without gating file actions", () => {+ const map = buildPolicyBadgeMap(+ [run({ status: "RUNNING", externalOutput: true, outputFileIds: [] })],+ [{ id: "in" }],+ labels,+ );+ expect(map.get("in")?.[0].background).toBe(true);+ expect(map.get("in")?.[0].enforcing).toBeUndefined();+});+describe("buildPolicyBadgeMap — in-flight indicators", () => {const enforcingOn = (map: Map<string, { enforcing?: boolean }[]>,diff --git a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.tsindex af8efcabba..14dc59c52d 100644--- a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts+++ b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts@@ -102,9 +102,10 @@ export function buildPolicyBadgeMap(if (settled && !run.retrying) continue;const name = labelById.get(run.policyKey);if (!name) continue;- const inFlightFlag = isClassificationPolicy(run.policyKey)- ? ("background" as const)- : ("enforcing" as const);+ const inFlightFlag =+ run.externalOutput || isClassificationPolicy(run.policyKey)+ ? ("background" as const)+ : ("enforcing" as const);const list = result.get(run.fileId) ?? [];const existing = list.find((p) => p.id === run.policyKey);if (existing) {diff --git a/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts b/frontend/editor/src/proprietary/services/notificationPolicyRetry.tsindex cd4733154e..a7fc04a11b 100644--- a/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts+++ b/frontend/editor/src/proprietary/services/notificationPolicyRetry.ts@@ -152,6 +152,7 @@ async function submit(fileName: document.name,fileSize: document.size,target: runTarget,+ externalOutput: loadPolicies()[policyKey]?.externalOutput,status: "PENDING",outputs: [],error: null,diff --git a/frontend/editor/src/proprietary/services/policyBackend.ts b/frontend/editor/src/proprietary/services/policyBackend.tsindex c35649dd33..2ea2234a9b 100644--- a/frontend/editor/src/proprietary/services/policyBackend.ts+++ b/frontend/editor/src/proprietary/services/policyBackend.ts@@ -53,6 +53,7 @@ export function decodedToState(owner: decoded.owner,sources: decoded.sources,runsOnEditor: decoded.runsOnEditor,+ externalOutput: decoded.externalOutput,required: decoded.required,scopeTypes: decoded.scopeTypes,reviewerEmail: decoded.reviewerEmail,diff --git a/frontend/editor/src/proprietary/services/policyDispatch.ts b/frontend/editor/src/proprietary/services/policyDispatch.tsindex f1771446f6..d414712d52 100644--- a/frontend/editor/src/proprietary/services/policyDispatch.ts+++ b/frontend/editor/src/proprietary/services/policyDispatch.ts@@ -40,6 +40,7 @@ export async function runPolicyOnFile(// Chained (downstream) dispatch — jumps the dispatch queue so a file mid-chain// finishes its flow before new files start (see acquireDispatchSlot).priority = false,+ externalOutput = false,): Promise<void> {// A freshly-uploaded file's bytes are written to IndexedDB asynchronously, so// its stub can appear in the file list a beat before getStirlingFile resolves@@ -72,6 +73,27 @@ export async function runPolicyOnFile(markDispatched(policyKey, fileId);return;}+ await dispatchPolicyFile(+ policyKey,+ backendId,+ file,+ fileId,+ priority,+ externalOutput,+ fileName,+ );+}++/** Submit a copy; external delivery records activity without importing results into the editor. */+export async function dispatchPolicyFile(+ policyKey: string,+ backendId: string,+ file: File,+ fileId?: string,+ priority = false,+ externalOutput = false,+ fileName = file.name,+): Promise<void> {// Bounded upload window — see MAX_CONCURRENT_DISPATCHES. Only the POST is// gated; the IDB wait above never holds a slot.const target = resolvePolicyRunTarget();@@ -85,8 +107,9 @@ export async function runPolicyOnFile(recordRunStart({runId,policyKey,- fileId,+ fileId: fileId ?? "",fileName,+ externalOutput,fileSize: file.size,target,status: "PENDING",@@ -100,10 +123,11 @@ export async function runPolicyOnFile(recordRunStart({runId: `dispatch-failed:${generateId()}`,policyKey,- fileId,+ fileId: fileId ?? "",fileName,fileSize: file.size,target,+ externalOutput,status: "FAILED",outputs: [],error: extractErrorMessage(err),diff --git a/frontend/editor/src/proprietary/services/policyExport.test.ts b/frontend/editor/src/proprietary/services/policyExport.test.tsindex d0794c64be..a3f676f3f5 100644--- a/frontend/editor/src/proprietary/services/policyExport.test.ts+++ b/frontend/editor/src/proprietary/services/policyExport.test.ts@@ -10,21 +10,27 @@ vi.mock("@app/services/policyStorage", () => ({const runStoredPolicy = vi.fn(async (_id: string, _files: File[]) => "run-1");const output = { name: "doc.pdf", type: "application/pdf" };+let serverExternalOutput = false;+const downloadPolicyOutput = vi.fn(+ async () => new Blob([], { type: output.type }),+);vi.mock("@app/services/policyApi", () => ({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",+ externalOutput: serverExternalOutput,outputs: [{ fileId: "out-1", fileName: output.name }],}),- downloadPolicyOutput: async () => new Blob([], { type: output.type }),+ downloadPolicyOutput: () => downloadPolicyOutput(),resolvePolicyRunTarget: () => "local",}));vi.mock("@app/components/policies/policyRunStore", () => ({recordRunStart: vi.fn(),isDispatched: () => false,+ markDispatched: vi.fn(),getPolicyRunOutcomes: () => ({}),}));// Run the queued task inline: the queue's own behaviour is not under test here.@@ -38,7 +44,13 @@ vi.mock("@app/components/toast", () => ({}));vi.mock("@app/i18n", () => ({ default: { t: (key: string) => key } }));+const dispatchPolicyFile = vi.hoisted(() =>+ vi.fn(() => new Promise<void>(() => {})),+);+vi.mock("@app/services/policyDispatch", () => ({ dispatchPolicyFile }));const { enforceExportPolicies } = await import("@app/services/policyExport");+const { recordRunStart } =+ await import("@app/components/policies/policyRunStore");/** An active export-time policy as the local store holds it. */const exportPolicy = (over: Partial<PolicyState>): PolicyState =>@@ -68,9 +80,32 @@ describe("export-time policy selection", () => {runStoredPolicy.mockClear();output.name = "doc.pdf";output.type = "application/pdf";+ serverExternalOutput = false;+ downloadPolicyOutput.mockClear();+ vi.mocked(recordRunStart).mockClear();});afterEach(() => vi.useRealTimers());+ it("records server-reported external delivery when cached metadata says internal", async () => {+ loadPolicies.mockReturnValue({+ ingestion: exportPolicy({ runsOnEditor: true, externalOutput: false }),+ });+ serverExternalOutput = true;+ const file = pdf();+ const pending = enforceExportPolicies([file], ["file-1"]);+ await vi.runAllTimersAsync();+ const result = await pending;+ expect(result[0].size).toBe(file.size);+ expect(downloadPolicyOutput).not.toHaveBeenCalled();+ expect(recordRunStart).toHaveBeenCalledWith(+ expect.objectContaining({+ fileId: "file-1",+ status: "COMPLETED",+ externalOutput: true,+ }),+ );+ });+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");@@ -172,6 +207,26 @@ describe("export-time policy selection", () => {]);});+ it("returns the exact original immediately while an external export submission is pending", async () => {+ loadPolicies.mockReturnValue({+ ingestion: exportPolicy({ runsOnEditor: true, externalOutput: true }),+ });+ const file = pdf();+ const files = [file];+ const result = await enforceExportPolicies(files, ["file-1"]);+ expect(result).toBe(files);+ expect(result[0]).toBe(file);+ expect(dispatchPolicyFile).toHaveBeenCalledWith(+ "ingestion",+ "backend-1",+ file,+ "file-1",+ false,+ true,+ );+ expect(runStoredPolicy).not.toHaveBeenCalled();+ });+it("enforces an editor pipeline set to run on export", async () => {loadPolicies.mockReturnValue({"builder-1": exportPolicy({diff --git a/frontend/editor/src/proprietary/services/policyExport.ts b/frontend/editor/src/proprietary/services/policyExport.tsindex a349108cae..3c8949c74c 100644--- a/frontend/editor/src/proprietary/services/policyExport.ts+++ b/frontend/editor/src/proprietary/services/policyExport.ts@@ -10,6 +10,7 @@* download. Each policy selects files using its first step's accepted inputs.*/+import { dispatchPolicyFile } from "@app/services/policyDispatch";import { loadPolicies } from "@app/services/policyStorage";import { assertFilesNotBlocked } from "@app/services/policyFileGuard";import { loadPolicyCatalog } from "@app/services/policyCatalog";@@ -27,6 +28,7 @@ import type { PolicyState } from "@app/types/policies";import {recordRunStart,isDispatched,+ markDispatched,} from "@app/components/policies/policyRunStore";import {runQueued,@@ -48,6 +50,7 @@ interface ExportPolicy extends Pick<PolicyState, "firstOperation"> {backendId: string;label: string;outputMode: "new_file" | "new_version";+ externalOutput?: boolean;required: boolean;/** The policy's accent as a CSS colour, for the toast glow. */accent: string;@@ -58,6 +61,7 @@ interface PolicyRunResult {runId: string;target: PolicyExecutionTarget;outputs: { fileId: string; fileName: string }[];+ externalOutput?: boolean;}/** Configured, active policies set to enforce on export (read from the cache). */@@ -76,6 +80,7 @@ function activeExportPolicies(): ExportPolicy[] {return {policyKey: id,backendId: s.backendId as string,+ externalOutput: s.externalOutput,firstOperation: s.firstOperation,// A builder pipeline has no built-in category, so it labels by its own name.label:@@ -111,6 +116,14 @@ async function runToCompletion(continue; // transient — keep polling within the cap.}if (view.status === "COMPLETED") {+ if (view.externalOutput)+ return {+ file,+ runId,+ target,+ outputs: view.outputs ?? [],+ externalOutput: true,+ };const out = view.outputs?.[0];if (!out) throw new Error("policy produced no output");const blob = await downloadPolicyOutput(out.fileId, target);@@ -160,7 +173,25 @@ export async function enforceExportPolicies(trigger: EnforcementTrigger = "export",): Promise<File[]> {assertFilesNotBlocked(fileIds);- const active = activeExportPolicies();+ const policies = activeExportPolicies();+ const active = policies.filter((policy) => !policy.externalOutput);+ const external = policies.filter((policy) => policy.externalOutput);+ for (const [i, file] of files.entries()) {+ const fileId = fileIds?.[i];+ for (const policy of external) {+ if (!policyAcceptsFile(policy, file)) continue;+ if (fileId && isDispatched(policy.policyKey, fileId)) continue;+ if (fileId) markDispatched(policy.policyKey, fileId);+ void dispatchPolicyFile(+ policy.policyKey,+ policy.backendId,+ file,+ fileId,+ false,+ true,+ );+ }+ }if (!active.length || files.length === 0) return files;// Policies that haven't already enforced this exact file version. Enforcing@@ -262,6 +293,7 @@ export async function enforceExportPolicies(target: versionRun.target,status: "COMPLETED",outputs: versionRun.outputs,+ externalOutput: versionRun.externalOutput,error: null,startedAt: Date.now(),});diff --git a/frontend/editor/src/proprietary/services/policyPipeline.ts b/frontend/editor/src/proprietary/services/policyPipeline.tsindex 752abffb2f..44c6ea6555 100644--- a/frontend/editor/src/proprietary/services/policyPipeline.ts+++ b/frontend/editor/src/proprietary/services/policyPipeline.ts@@ -52,6 +52,7 @@ export interface BackendPolicy {trigger: BackendTriggerConfig | null;steps: BackendPipelineStep[];output: BackendOutputSpec;+ outputIds?: string[];/** Whether the editor runs this policy per file, and on which moment. */editor?: BackendEditorConfig;/** A policy (blocking on failure) rather than an ordinary pipeline; see Policy.required. */@@ -105,6 +106,7 @@ export interface PolicyRunView {*/errorSubscribed?: boolean | null;outputs: BackendResultFile[];+ externalOutput?: boolean;/** When the run was created (epoch millis); lets a rediscovered run show its real age. */createdAt: number;}@@ -125,6 +127,7 @@ export interface DecodedPolicy {sources: string[];/** Whether the editor runs this policy per file, straight from the policy's own flag. */runsOnEditor: boolean;+ externalOutput?: boolean;/** A policy (blocking on failure) rather than an ordinary pipeline (see Policy.required). */required: boolean;scopeTypes: string[];@@ -175,6 +178,8 @@ export function fromBackendPolicy(policy: BackendPolicy): DecodedPolicy {fieldValues:(meta.fieldValues as DecodedPolicy["fieldValues"] | undefined) ?? {},runsOnEditor: editor?.allowed === true,+ externalOutput:+ Boolean(policy.outputIds?.length) || policy.output.type !== "inline",required: policy.required === true,folder: {runOn: resolveRunOn(editor?.runOn, policyKey),diff --git a/frontend/editor/src/proprietary/types/policies.ts b/frontend/editor/src/proprietary/types/policies.tsindex 24df76fe48..0dc83028f6 100644--- a/frontend/editor/src/proprietary/types/policies.ts+++ b/frontend/editor/src/proprietary/types/policies.ts@@ -64,6 +64,7 @@ export interface PolicyState {/** How a run's output is delivered: a separate new file, or a new version of* the input file the policy ran on. Defaults to "new_version". */outputMode?: "new_file" | "new_version";+ externalOutput?: boolean;/** Rename rule for the output. When empty (the default) the output keeps the* input's filename; when set, it's applied as a prefix/suffix per the policy's* name-position setting. */