#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
Add source and output setup to ingestion policies (#7991)
Anthony Stirlingf43e39773792
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/DocParseController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/DocParseController.javaindex be5795430a..210359b544 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/DocParseController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/DocParseController.java@@ -12,6 +12,7 @@ import org.springframework.core.io.Resource;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@@ -60,6 +61,12 @@ public class DocParseController {private final ObjectMapper objectMapper;private final TempFileManager tempFileManager;+ @GetMapping("/capabilities")+ @Operation(summary = "Current ingestion and indexing readiness for guided policy setup")+ public DocParseService.Capabilities capabilities() {+ return docParseService.capabilities();+ }+@AutoJobPostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE,value = "/ingest",diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.javaindex bf04800a3b..93d571bf2b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java@@ -237,9 +237,14 @@ public class ProcessingFolderController {request.routingRules() != null? request.routingRules(): existing == null ? List.of() : existing.routingRules();+ List<PipelineStep> steps = request.steps() == null ? List.of() : request.steps();+ if (steps.stream().anyMatch(Objects::isNull)) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Pipeline steps must not be null");+ }Stream.concat(outputIds.stream(), routingRules.stream().map(RoutingRule::outputId)).distinct()- .forEach(outputId -> requireAccessibleDestination(outputId, request.steps()));+ .forEach(outputId -> requireAccessibleDestination(outputId, steps));String name = onDisk ? diskFolderName(request.directory()) : folder.getName();// Held for rollback: the source is written before the policy validates, and a rejected@@ -280,7 +285,7 @@ public class ProcessingFolderController {: new TriggerConfig(TriggerConfig.STORAGE_FOLDER_WATCH,Map.of()))),- request.steps() == null ? List.of() : request.steps(),+ steps,outputSpecFor(request, folder),outputIds,policyAccessGuard.teamForNewPolicy(),@@ -880,6 +885,14 @@ public class ProcessingFolderController {DISK_SWEEP_LIMIT);}+ private static boolean exportsCorpus(SaveProcessingFolderRequest request) {+ if (request.steps() == null || request.steps().isEmpty()) return false;+ PipelineStep last = request.steps().getLast();+ return "/api/v1/docparse/ingest".equals(last.operation())+ && ("true".equals(String.valueOf(last.parameters().get("exportChunksJsonl")))+ || "true".equals(String.valueOf(last.parameters().get("exportMarkdown"))));+ }+/** The trailing path segment ("Downloads"), or the raw path when it has none. */private static String diskFolderName(String directory) {Path path = Path.of(directory.trim());@@ -888,6 +901,16 @@ public class ProcessingFolderController {}private void requireAccessibleDestination(String outputId, List<PipelineStep> steps) {+ Source destination = accessibleDestination(outputId);+ // Validate on the request thread: connection checks need the caller's authentication.+ try {+ policyValidator.validateOutput(destination.toOutputSpec(), steps);+ } catch (IllegalArgumentException e) {+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());+ }+ }++ private Source accessibleDestination(String outputId) {Source destination =sourceStore.get(outputId)@@ -902,32 +925,28 @@ public class ProcessingFolderController {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The editor can't be used as an output destination");}- // Validate on the request thread: connection checks need the caller's authentication.- try {- policyValidator.validateOutput(destination.toOutputSpec(), steps);- } catch (IllegalArgumentException e) {- throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());+ // Dispatch resolves the destination again on a worker thread with no caller to report to.+ if (!destination.enabled()) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "The output destination is disabled: " + outputId);}+ return destination;}- /**- * Both kinds process in place — the folder's contents become their processed selves. The sink- * records each replacement in the ledger at the result's version and the input settles its- * claim the same way, so a sweep never mistakes the folder's own output for new work. Disk- * output is what works on an install with no accounts and no file storage.- */+ /** Corpus exports preserve originals; ordinary PDF processing replaces them. */private OutputSpec outputSpecFor(SaveProcessingFolderRequest request, Folder folder) {Map<String, Object> options =new HashMap<>(request.output() == null ? Map.of() : request.output());if (folder != null) {+ if (exportsCorpus(request)) options.put("mode", "new_file");// Force the output to the caller-owned source folder: the storage sink only checks a// folderId exists, not that the caller owns it, so honouring a request-supplied one- // would write output into another tenant's folder. Processing is in place anyway.+ // would write output into another tenant's folder. Results remain in this folder.options.put("folderId", folder.getId().toString());return new OutputSpec("storage", options);}options.put("directory", request.directory().trim());- options.put("replace", true);+ options.put("replace", !exportsCorpus(request));return new OutputSpec("folder", options);}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.javaindex e76bd2811c..378a9225e6 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java@@ -82,6 +82,32 @@ public class DocParseService {}}+ /** Live readiness for guided setup; unavailable engines cannot enable ingestion policies. */+ public record Capabilities(+ boolean enabled, boolean engineReachable, boolean indexingConfigured) {}++ private record EngineCapabilities(boolean indexingConfigured) {}++ /**+ * Probe current engine readiness without ingesting documents or calling an embedding provider.+ */+ public Capabilities capabilities() {+ boolean enabled = applicationProperties.getDocparse().isEnabled();+ if (!enabled || !applicationProperties.getAiEngine().isEnabled()) {+ return new Capabilities(enabled, false, false);+ }+ try {+ EngineCapabilities result =+ objectMapper.readValue(+ aiEngineClient.get("/api/v1/docparse/capabilities", currentUserId()),+ EngineCapabilities.class);+ return new Capabilities(enabled, true, result.indexingConfigured());+ } catch (IOException | RuntimeException e) {+ log.debug("Could not check ingestion readiness: {}", e.getMessage());+ return new Capabilities(enabled, false, false);+ }+ }+/*** Convert the document to Markdown blocks, then chunk, embed, and index them into the engine's* knowledge base and/or hand them back for corpus export.diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.javaindex b46d359971..df7039ff57 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java@@ -5,9 +5,11 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.atLeastOnce;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.timeout;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;@@ -209,6 +211,116 @@ class ProcessingFolderControllerTest {properties);}+ @Test+ void aDestinationRefusesAPipelineItCannotDeliver() {+ Source destination =+ sourceStore.save(+ new Source(+ null,+ "Corpus",+ "folder",+ Map.of("directory", tempDir.toString()),+ true,+ "reece",+ 3L));+ var baseline = request(null, "new_version");+ // Stubbed on the request's own steps: the sink has to see them, not an empty list.+ doThrow(new IllegalArgumentException("requires a final AI ingestion step"))+ .when(diskFolderSink)+ .validatePipeline(any(), eq(baseline.steps()));+ var unsupported =+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ FOLDER_ID.toString(),+ null,+ true,+ baseline.steps(),+ Map.of(),+ List.of(destination.id()),+ List.of());+ assertThatThrownBy(() -> controller.save(unsupported))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("AI ingestion step");+ assertThat(policyStore.all()).isEmpty();+ }++ @Test+ void aRoutedDestinationValidatesTheFoldersPipelineOutput() {+ Source routed =+ sourceStore.save(+ new Source(+ null,+ "Invoices",+ "folder",+ Map.of("directory", tempDir.toString()),+ true,+ "reece",+ 3L));+ var routes =+ List.of(+ new RoutingRule(+ new Condition.MatchesAny(+ new ConditionInput.DocumentField("document.extension"),+ List.of("pdf")),+ routed.id()));+ var baseline = request(null, "new_version");+ var created =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ FOLDER_ID.toString(),+ null,+ true,+ baseline.steps(),+ Map.of("categoryId", "routing"),+ List.of(),+ routes))+ .getBody();+ assertThat(created.routingRules()).isEqualTo(routes);+ verify(diskFolderSink, atLeastOnce())+ .validatePipeline(routed.toOutputSpec(), baseline.steps());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void aDisabledDestinationIsRefusedWhileThereIsStillACallerToTellAboutIt(boolean routeOnly) {+ Source destination =+ sourceStore.save(+ new Source(+ null,+ "Paused corpus",+ "folder",+ Map.of("directory", tempDir.toString()),+ false,+ "reece",+ 3L));+ var baseline = request(null, "new_version");+ var paused =+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ FOLDER_ID.toString(),+ null,+ true,+ baseline.steps(),+ Map.of(),+ routeOnly ? List.of() : List.of(destination.id()),+ routeOnly+ ? List.of(+ new RoutingRule(+ new Condition.MatchesAny(+ new ConditionInput.DocumentField(+ "document.extension"),+ List.of("pdf")),+ destination.id()))+ : List.of());+ assertThatThrownBy(() -> controller.save(paused))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("disabled");+ assertThat(policyStore.all()).isEmpty();+ verify(diskFolderSink, never()).validatePipeline(any(), any());+ }+@Testvoid routingTemplatePersistsDestinationsAndRetainsThemAcrossPauseRequests() {Source destination =@@ -410,6 +522,60 @@ class ProcessingFolderControllerTest {.doesNotContainValue(foreign);}+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void aNullFinalStepIsRejectedBeforeCreatingTheFolderPair(boolean onDisk) {+ var malformed =+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ onDisk ? null : FOLDER_ID.toString(),+ onDisk ? tempDir.toString() : null,+ true,+ Stream.of((PipelineStep) null).toList(),+ Map.of());++ assertThatThrownBy(() -> controller.save(malformed))+ .isInstanceOfSatisfying(+ ResponseStatusException.class,+ error ->+ assertThat(error.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST))+ .hasMessageContaining("Pipeline steps must not be null");+ assertThat(policyStore.all()).isEmpty();+ assertThat(sourceStore.all()).isEmpty();+ verifyNoInteractions(policyRunner);+ }++ @ParameterizedTest+ @ValueSource(strings = {"exportChunksJsonl", "exportMarkdown"})+ void corpusExportsPreserveOriginalsInStorageAndOnDisk(String exportFlag) {+ var steps =+ List.of(+ new PipelineStep(+ "/api/v1/docparse/ingest",+ Map.of("index", false, exportFlag, true),+ Map.of()));+ var stored =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null,+ FOLDER_ID.toString(),+ null,+ true,+ steps,+ Map.of("mode", "new_version")))+ .getBody();+ assertThat(stored.output()).containsEntry("mode", "new_file");++ var disk =+ controller+ .save(+ new ProcessingFolderController.SaveProcessingFolderRequest(+ null, null, tempDir.toString(), true, steps, Map.of()))+ .getBody();+ assertThat(disk.output()).containsEntry("replace", false);+ }+@Testvoid aCreateOverAnExistingPlaceAdoptsItWithoutReconfiguring() {var first = controller.save(request(null, "new_version")).getBody();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.javaindex 6e7245a167..af3d9c8524 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/DocParseServiceTest.java@@ -82,6 +82,35 @@ class DocParseServiceTest {userService);}+ @Test+ void capabilitiesDistinguishesCorpusExportFromConfiguredIndexing() throws IOException {+ properties.getDocparse().setEnabled(true);+ properties.getAiEngine().setEnabled(true);+ when(aiEngineClient.get("/api/v1/docparse/capabilities", null))+ .thenReturn("{\"indexingConfigured\":false}", "{\"indexingConfigured\":true}");++ assertEquals(new DocParseService.Capabilities(true, true, false), service.capabilities());+ assertEquals(new DocParseService.Capabilities(true, true, true), service.capabilities());+ }++ @Test+ void capabilitiesReportsAnUnreachableEngine() throws IOException {+ properties.getDocparse().setEnabled(true);+ properties.getAiEngine().setEnabled(true);+ when(aiEngineClient.get("/api/v1/docparse/capabilities", null))+ .thenThrow(new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE));++ assertEquals(new DocParseService.Capabilities(true, false, false), service.capabilities());+ }++ @Test+ void capabilitiesDoesNotProbeWhenIngestionIsDisabled() {+ properties.getDocparse().setEnabled(false);++ assertEquals(new DocParseService.Capabilities(false, false, false), service.capabilities());+ verifyNoInteractions(aiEngineClient);+ }+private static byte[] pdfBytes(int pages) throws IOException {try (PDDocument document = new PDDocument();ByteArrayOutputStream out = new ByteArrayOutputStream()) {diff --git a/engine/src/stirling/api/routes/docparse.py b/engine/src/stirling/api/routes/docparse.pyindex d0b2640799..2ff9375307 100644--- a/engine/src/stirling/api/routes/docparse.py+++ b/engine/src/stirling/api/routes/docparse.py@@ -13,7 +13,7 @@ from fastapi import APIRouter, Depends, HTTPException, statusfrom stirling.api.dependencies import get_document_service, require_user_idfrom stirling.config import AppSettings, load_settings-from stirling.contracts.docparse import DocChunk, IngestRequest, IngestResponse+from stirling.contracts.docparse import DocChunk, DocparseCapabilities, IngestRequest, IngestResponsefrom stirling.docparse.chunking import pack_blocks, page_textsfrom stirling.documents import DocumentServicefrom stirling.documents.service import CONTENT_TYPE_METADATA_KEY, DOCPARSE_CHUNK_CONTENT_TYPE@@ -28,6 +28,12 @@ def _settings() -> AppSettings:return load_settings()[email protected]("/capabilities", response_model=DocparseCapabilities)+async def capabilities(documents: Annotated[DocumentService, Depends(get_document_service)]) -> DocparseCapabilities:+ """Report live embedding readiness for guided ingestion setup."""+ return DocparseCapabilities(indexing_configured=documents.embedder.configured)++def _chunk_metadata(chunk: DocChunk) -> dict[str, str]:meta = {CONTENT_TYPE_METADATA_KEY: DOCPARSE_CHUNK_CONTENT_TYPE}if chunk.page_start is not None:diff --git a/engine/src/stirling/contracts/docparse.py b/engine/src/stirling/contracts/docparse.pyindex 12b7c60baf..b3e6a5a87c 100644--- a/engine/src/stirling/contracts/docparse.py+++ b/engine/src/stirling/contracts/docparse.py@@ -15,6 +15,10 @@ from pydantic import Fieldfrom stirling.models import ApiModel, FileId, OwnerId, PrincipalId+class DocparseCapabilities(ApiModel):+ indexing_configured: bool++class MarkdownBlock(ApiModel):"""One rendered Markdown element and the 1-based pages it came from.diff --git a/engine/src/stirling/documents/embedder.py b/engine/src/stirling/documents/embedder.pyindex 4ab0508a74..884c05aae4 100644--- a/engine/src/stirling/documents/embedder.py+++ b/engine/src/stirling/documents/embedder.py@@ -1,12 +1,15 @@from __future__ import annotations+from openai import OpenAIErrorfrom pydantic_ai import Embedder+from pydantic_ai.embeddings import infer_embedding_modelfrom pydantic_ai.embeddings.openai import OpenAIEmbeddingModel+from pydantic_ai.exceptions import UserErrorfrom pydantic_ai.providers.openai import OpenAIProviderfrom stirling.documents.chunker import chunk_textfrom stirling.documents.store import Document-from stirling.documents.voyage import build_voyage_model+from stirling.documents.voyage import VoyageEmbeddingModel, build_voyage_model# Keep each upstream embed request under every major provider's per-call limit while# still batching large enough that a book-sized document ingests in a reasonable number@@ -64,6 +67,15 @@ class EmbeddingService:self._chunk_overlap = chunk_overlapself._embed_batch_size = embed_batch_size+ @property+ def configured(self) -> bool:+ """Check local provider configuration without embedding or writing documents."""+ try:+ model = infer_embedding_model(self._embedder.model)+ except (ValueError, ImportError, UserError, OpenAIError):+ return False+ return model.configured if isinstance(model, VoyageEmbeddingModel) else True+async def embed_query(self, text: str) -> list[float]:"""Embed a search query, optimised for retrieval."""result = await self._embedder.embed_query(text)diff --git a/engine/src/stirling/documents/voyage.py b/engine/src/stirling/documents/voyage.pyindex e308f32ec9..87a4b06e59 100644--- a/engine/src/stirling/documents/voyage.py+++ b/engine/src/stirling/documents/voyage.py@@ -24,6 +24,11 @@ _MISSING_API_KEY = "stirling-voyage-api-key-not-configured"class VoyageEmbeddingModel(OpenAIEmbeddingModel):"""Voyage embeddings spoken over the OpenAI wire format."""+ @property+ def configured(self) -> bool:+ """Whether the client has credentials; this does not make a provider request."""+ return self._client.api_key != _MISSING_API_KEY+async def embed(self,inputs: str | Sequence[str],diff --git a/engine/tests/docparse/test_ingest.py b/engine/tests/docparse/test_ingest.pyindex e88564a471..533adf3c03 100644--- a/engine/tests/docparse/test_ingest.py+++ b/engine/tests/docparse/test_ingest.py@@ -35,6 +35,7 @@ class StubDocumentService:def __init__(self) -> None:self.calls: list[dict[str, Any]] = []+ self.embedder = StubEmbedder()async def ingest_prepared(self,@@ -65,6 +66,7 @@ class StubEmbedder:def __init__(self, dim: int = 8) -> None:self._dim = dim+ self.configured = Trueasync def embed_query(self, text: str) -> list[float]:h = hash(text) % 1000@@ -88,6 +90,16 @@ def client(stub_service: StubDocumentService) -> Iterator[TestClient]:app.dependency_overrides.pop(get_document_service, None)[email protected]("configured", [True, False])+def test_capabilities_reports_live_embedding_readiness(+ client: TestClient, stub_service: StubDocumentService, configured: bool+) -> None:+ stub_service.embedder.configured = configured+ response = client.get("/api/v1/docparse/capabilities", headers=HEADERS)+ assert response.status_code == 200+ assert response.json() == {"indexingConfigured": configured}++def test_ingest_indexes_chunks_with_metadata(client: TestClient, stub_service: StubDocumentService) -> None:response = client.post("/api/v1/docparse/ingest",diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 1187ffb881..7245893e57 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -9282,7 +9282,7 @@ desc = "Strip hidden data, convert to PDF/A for archiving, and validate every dolabel = "Compliance"[portal.policies.categories.ingestion]-desc = "Classify documents, extract structured data, enforce naming conventions, and normalize pages."+description = "Read documents, prepare searchable chunks, and deliver them to a knowledge base or export destination."label = "Ingestion"[portal.policies.categories.retention]@@ -9316,13 +9316,13 @@ summary = "Strips hidden data, converts to the PDF/A archival format, and valida2 = "Validate compliance"[portal.policies.config.ingestion]-summary = "Classifies documents, extracts structured data, enforces naming, and normalizes pages."+description = "Choose the documents to process, make their text searchable, and send chunks to a database or export them."[portal.policies.config.ingestion.rules]-0 = "Classify"-1 = "Extract"-2 = "Name"-3 = "Normalize"+0 = "Read text"+1 = "Chunk"+2 = "Index"+3 = "Keep the original"[portal.policies.config.pdfa.fields.outputFormat]help = "PDF/A-2b suits most archives. PDF/A-1b is the strictest and most widely accepted; PDF/A-3b additionally allows attachments."@@ -9647,11 +9647,43 @@ noTools = "Enable at least one action."saveFailed = "Couldn't save the pipeline. Please try again."[portal.policies.wizard.locations]+aiSettings = "Open AI settings"+builtin = "Stirling knowledge base"+builtinHelp = "Indexes searchable chunks in Stirling and returns the processed PDF to the destination below. An embedding provider must be configured in AI settings."+checking = "Checking ingestion availability..."+chooseOutput = "Choose an enabled output destination before saving."+chooseSource = "Choose where documents come from"+chunkSettings = "Chunk settings"+connectInput = "Connect input source"+consumed = "Check this source's processing mode: consume deletes originals after a successful run. Choose Track in Edit input source to keep them."delivery = "Delivery"+desktopExternal = "Manage this database connection in the web app’s Processor, or change the output type to return results to this folder."+destination = "Destination"+editInput = "Edit input source"+editor = "Files opened in the editor"+editorDestination = "Editor workspace"editorOutput = "Processed PDFs return to the editor workspace."+engineUnavailable = "The AI engine is disabled or unreachable. Enable it to prepare chunks, or turn off knowledge search to run OCR only."+export = "Export chunks without a database"+exportHelp = "Saves the processed PDF and chunks (JSONL) to the destination below. The AI engine prepares the chunks; no database or embedding provider is needed."+external = "Connected vector database"+externalHelp = "Sends chunks to the selected database, which generates embeddings. The run returns an indexing receipt."+folder = "Input: {{name}}. Originals are retained when delivering to a vector database."+folderOutput = "Processed files are saved in this folder. Corpus exports keep the original PDF."+indexingUnavailable = "The built-in knowledge base needs an embedding provider. Configure one in AI settings, connect a vector database, or export chunks without a database."+input = "Documents to process"+invalidChunks = "Choose a chunk size from 64 to 32768 and an overlap from 0 to 4096 smaller than the chunk size."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."+noDatabase = "No vector database destination is set up. Connect a source below, then choose or create its database connection and collection."+output = "Output"+outputType = "Output type"+recheck = "Check again"+retained = "This source does not delete inputs after processing. Choose a separate destination to keep the original files unchanged."returnToEditor = "Return results to editor"+returnToFolder = "Return results to this folder"+savedDatabase = "Saved vector database"+source = "Input source"[portal.policies.wizard.routing]chooseDestination = "Choose a destination"diff --git a/frontend/editor/src/desktop/components/policies/FolderPolicySetupConfig.test.tsx b/frontend/editor/src/desktop/components/policies/FolderPolicySetupConfig.test.tsxnew file mode 100644index 0000000000..a86c17e426--- /dev/null+++ b/frontend/editor/src/desktop/components/policies/FolderPolicySetupConfig.test.tsx@@ -0,0 +1,152 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { FolderPolicySetupConfig } from "@app/components/policies/FolderPolicySetupConfig";+import type { PolicySetupResult } from "@app/policies/catalog";+import { policyStep, policyStepToWire } from "@app/policies/operations";++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: vi.fn() },+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));+vi.mock("@app/services/apiClient", () => ({+ default: {+ get: () =>+ Promise.resolve({+ data: {+ enabled: true,+ engineReachable: true,+ indexingConfigured: false,+ },+ }),+ },+}));+vi.mock("@app/ui", () => ({+ FormField: ({+ label,+ children,+ }: {+ label: string;+ children: React.ReactNode;+ }) => (+ <label>+ {label}+ {children}+ </label>+ ),+ Input: ({ value, readOnly }: { value: string; readOnly: boolean }) => (+ <input value={value} readOnly={readOnly} />+ ),+ Banner: ({ description }: { description: string }) => <p>{description}</p>,+ Button: ({+ children,+ onClick,+ }: {+ children: React.ReactNode;+ onClick: () => void;+ }) => <button onClick={onClick}>{children}</button>,+}));+vi.mock("@app/components/policies/PolicyIngestionConfig", () => ({+ PolicyIngestionConfig: ({+ onTargetChange,+ allowExternal,+ children,+ }: {+ onTargetChange: (target: string) => void;+ allowExternal: boolean;+ children: React.ReactNode;+ }) => (+ <>+ {children}+ <button+ onClick={() => onTargetChange("export")}+ data-external={allowExternal}+ >+ Export without a database+ </button>+ </>+ ),+}));+function mount(+ steps = [policyStepToWire(policyStep("ingest"))],+ outputIds: string[] = [],+) {+ const onChange = vi.fn();+ const onValidityChange = vi.fn();+ const result: PolicySetupResult = {+ required: false,+ runsOnEditor: false,+ sources: [],+ scopeTypes: [],+ reviewerEmail: "",+ fieldValues: {},+ outputMode: "new_version",+ outputName: "",+ outputNamePosition: "suffix",+ runOn: "upload",+ maxRetries: 0,+ retryDelayMinutes: 0,+ steps,+ outputIds,+ };+ render(+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <FolderPolicySetupConfig+ result={result}+ onChange={onChange}+ onValidityChange={onValidityChange}+ folderName="Documents"+ />+ </QueryClientProvider>,+ );+ return { onChange, onValidityChange };+}+describe("desktop folder policy settings", () => {+ it("offers corpus export without importing Processor or requiring an embedding provider", async () => {+ const { onChange, onValidityChange } = mount();+ await waitFor(() =>+ expect(onValidityChange).toHaveBeenLastCalledWith(false),+ );+ expect(screen.getByRole("region", { name: "Output" })).toBeInTheDocument();+ expect(screen.getByRole("textbox", { name: "Destination" })).toHaveValue(+ "Documents",+ );+ const button = screen.getByRole("button", {+ name: "Export without a database",+ });+ expect(button).toHaveAttribute("data-external", "false");+ fireEvent.click(button);+ expect(onChange).toHaveBeenLastCalledWith(+ expect.objectContaining({+ outputIds: [],+ steps: [+ expect.objectContaining({+ parameters: expect.objectContaining({+ index: false,+ includeOriginal: true,+ exportChunksJsonl: true,+ }),+ }),+ ],+ }),+ );+ });+ it("preserves an existing external target until the user returns results to the folder", () => {+ const { onChange, onValidityChange } = mount(+ [policyStepToWire(policyStep("ocr"))],+ ["saved-database"],+ );+ expect(onValidityChange).toHaveBeenLastCalledWith(false);+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole("button", { name: "Return results to this folder" }),+ );+ expect(onChange).toHaveBeenLastCalledWith(+ expect.objectContaining({ outputIds: [] }),+ );+ });+});diff --git a/frontend/editor/src/desktop/components/policies/FolderPolicySetupConfig.tsx b/frontend/editor/src/desktop/components/policies/FolderPolicySetupConfig.tsxnew file mode 100644index 0000000000..5b99a698b1--- /dev/null+++ b/frontend/editor/src/desktop/components/policies/FolderPolicySetupConfig.tsx@@ -0,0 +1 @@+export { FolderIngestionSettings as FolderPolicySetupConfig } from "@app/components/policies/FolderIngestionSettings";diff --git a/frontend/editor/src/portal/api/docparse.ts b/frontend/editor/src/portal/api/docparse.tsnew file mode 100644index 0000000000..02f16f6bbe--- /dev/null+++ b/frontend/editor/src/portal/api/docparse.ts@@ -0,0 +1,14 @@+import { apiClient } from "@portal/api/http";++export interface DocparseCapabilities {+ enabled: boolean;+ engineReachable: boolean;+ indexingConfigured: boolean;+}++/** Probe current ingestion readiness before saving a guided policy. */+export function fetchDocparseCapabilities(): Promise<DocparseCapabilities> {+ return apiClient.local.json<DocparseCapabilities>(+ "/api/v1/docparse/capabilities",+ );+}diff --git a/frontend/editor/src/portal/api/policies.test.ts b/frontend/editor/src/portal/api/policies.test.tsindex 1d280b3849..a89b0cf1de 100644--- a/frontend/editor/src/portal/api/policies.test.ts+++ b/frontend/editor/src/portal/api/policies.test.ts@@ -1,9 +1,10 @@import { describe, expect, it } from "vitest";import {- buildWireFromSetup,assemblePolicies,+ buildWireFromSetup,parseSimplePolicy,type PolicySetupResult,+ type WirePolicy,} from "@portal/api/policies";import { policyStep, policyStepToWire } from "@app/policies/operations";import type { Policy } from "@portal/api/pipelines";@@ -166,3 +167,120 @@ describe("buildWireFromSetup", () => {expect(wire.name).toBe("My classifier");});});++it("round-trips source bindings, schedule, paused state and database target", () => {+ const policy: Policy = {+ ...classificationPolicy(false),+ name: "Archive ingestion",+ enabled: false,+ icon: "database",+ inputs: [+ {+ sourceId: "incoming",+ trigger: {+ type: "schedule",+ options: { schedule: { type: "every", count: 15, unit: "MINUTES" } },+ },+ },+ ],+ outputIds: ["knowledge"],+ editor: { allowed: false, runOn: "upload" },+ steps: [+ policyStepToWire(policyStep("ocr", { languages: ["eng"] })),+ policyStepToWire(+ policyStep("ingest", {+ index: "false",+ includeOriginal: "false",+ exportChunksJsonl: "true",+ }),+ ),+ ],+ output: {+ type: "inline",+ options: { categoryId: "ingestion", customMetadata: "kept" },+ },+ };+ const entry = parseSimplePolicy(policy, [])!;+ expect(entry).not.toBeNull();+ const result = {+ ...setupResult(),+ runsOnEditor: false,+ inputs: entry.policy!.state.inputs,+ outputIds: entry.policy!.state.outputIds,+ steps: entry.policy!.steps,+ extraOptions: entry.policy!.state.extraOptions,+ };+ const wire = buildWireFromSetup(entry, result, t, false);+ expect(wire.inputs).toEqual(policy.inputs);+ expect(wire.outputIds).toEqual(["knowledge"]);+ expect(wire.steps).toEqual(policy.steps);+ expect(wire.output.options).toMatchObject({ customMetadata: "kept" });+ expect(wire.enabled).toBe(false);+ expect(wire.name).toBe("Archive ingestion");+ expect(wire.icon).toBe("database");+});++it("keeps advanced triggers and inline output types in the full builder", () => {+ const policy = classificationPolicy(false);+ expect(+ parseSimplePolicy(+ {+ ...policy,+ inputs: [+ {+ sourceId: "in",+ trigger: {+ type: "schedule",+ options: { schedule: { type: "cron", expression: "0 0 * * *" } },+ },+ },+ ],+ },+ [],+ ),+ ).toBeNull();+ expect(+ parseSimplePolicy(+ {+ ...policy,+ output: { type: "folder", options: { categoryId: "classification" } },+ },+ [],+ ),+ ).toBeNull();+});++it("preserves source bindings and custom identity through catalogue setup links", () => {+ const policy: WirePolicy = {+ id: "contracts-policy",+ steps: [policyStepToWire(policyStep("classify"))],+ output: { type: "inline", options: { categoryId: "classification" } },+ name: "Contracts classifier",+ icon: "shield",+ enabled: false,+ inputs: [{ sourceId: "contracts", trigger: null }],+ outputIds: ["archive"],+ };+ const entry = assemblePolicies([policy], []).catalogue.find(+ (entry) => entry.category.id === "classification",+ )!;+ const state = entry.policy!.state;+ const wire = buildWireFromSetup(+ entry,+ {+ ...setupResult(),+ inputs: state.inputs,+ outputIds: state.outputIds,+ runsOnEditor: false,+ },+ t,+ false,+ );+ expect(wire).toMatchObject({+ name: policy.name,+ icon: policy.icon,+ enabled: false,+ inputs: policy.inputs,+ outputIds: policy.outputIds,+ });+});diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.tsindex b200a1e4b8..5a9729b885 100644--- a/frontend/editor/src/portal/api/policies.ts+++ b/frontend/editor/src/portal/api/policies.ts@@ -78,9 +78,8 @@ function isOrderedSubset<T>(inner: T[], outer: T[]): boolean {/*** The CatalogueEntry that seeds the simple wizard for a policy, or null if the wizard can't express- * it losslessly - the single authority for routing an edit to the wizard vs the full builder. Null on- * anything the wizard can't show: no template origin, a server input/destination, an unknown or extra- * tool, or a reordered chain.+ * it losslessly. Unsupported triggers, multiple locations, extra tools and reordered chains+ * stay in the full builder.*/export function parseSimplePolicy(policy: Policy,@@ -93,10 +92,32 @@ export function parseSimplePolicy(const config = POLICY_CONFIG[categoryId];if (!category || !config) return null;- // The wizard only runs on the editor (sources + runOn live in the options bag, not as server- // inputs/destinations). A policy carrying either cannot be shown simply.- if ((policy.inputs?.length ?? 0) > 0) return null;- if ((policy.outputIds?.length ?? 0) > 0) return null;+ if ((policy.inputs?.length ?? 0) > 1 || (policy.outputIds?.length ?? 0) > 1)+ return null;+ if (policy.output?.type && policy.output.type !== "inline") return null;+ if (policy.editor?.allowed && policy.inputs?.length) return null;++ const trigger = policy.inputs?.[0]?.trigger;+ if (trigger) {+ if (!["schedule", "folder-watch"].includes(trigger.type)) return null;+ const options = trigger.options ?? {};+ if (trigger.type === "folder-watch" && Object.keys(options).length > 0)+ return null;+ if (trigger.type === "schedule") {+ const schedule = options.schedule as+ | { type?: string; unit?: string; count?: number }+ | undefined;+ if (+ Object.keys(options).some((key) => key !== "schedule") ||+ schedule?.type !== "every" ||+ !["MINUTES", "HOURS", "DAYS"].includes(schedule.unit ?? "") ||+ Object.keys(schedule).some(+ (key) => !["type", "unit", "count"].includes(key),+ )+ )+ return null;+ }+ }// Every step must be one of this template's capabilities, and they must stay in canonical order.const canonical = config.defaultOperations.map((op) => op.toolId);@@ -111,6 +132,7 @@ export function parseSimplePolicy(const wire: WirePolicy = {id: policy.id ?? "",name: policy.name,+ icon: policy.icon,enabled: policy.enabled,required: policy.required,inputs: policy.inputs ?? [],@@ -128,14 +150,19 @@ export function parseSimplePolicy((entry) => entry.category.id === categoryId,)?.policy;if (!decorated) return null;- // The wire codec models neither the icon nor the (custom) name; carry them from the raw record so- // the Customise hand-off preserves them instead of resetting to the category default.+return {category,config,policy: {...decorated,- state: { ...decorated.state, name: policy.name, icon: policy.icon },+ state: {+ ...decorated.state,+ name: policy.name,+ icon: policy.icon,+ inputs: policy.inputs ?? [],+ outputIds: policy.outputIds ?? [],+ },},};}@@ -187,7 +214,7 @@ type CatalogueWireBody = WirePolicy & { categoryId: string; icon?: string };* otherwise the raw key is persisted and surfaces in the UI (e.g. the Sources* "Used by" pill).*/-function policyDisplayName(entry: CatalogueEntry, t: TFunction): string {+export function policyDisplayName(entry: CatalogueEntry, t: TFunction): string {return t("portal.policies.defaultName", {category: t(entry.category.label),});@@ -203,19 +230,22 @@ export function buildWireFromSetup(const stored = entry.policy?.state;return {categoryId: entry.category.id,- icon: stored?.icon,...toWirePolicy({id: stored?.backendId ?? "",name: stored?.name ?? policyDisplayName(entry, t),+ icon: stored?.icon,enabled,required: result.required,extraOptions: result.extraOptions,policyKey: entry.category.id,- inputs: policyInputs(result.sources, result.trigger ?? null),+ inputs:+ result.trigger !== undefined+ ? policyInputs(result.sources, result.trigger)+ : (result.inputs ?? stored?.inputs ?? []),trigger: result.trigger ?? null,- outputIds: result.outputIds ?? stored?.outputIds ?? [],routingRules: result.routingRules ?? stored?.routingRules ?? [],sources: result.sources,+ outputIds: result.outputIds ?? stored?.outputIds ?? [],runsOnEditor: result.runsOnEditor,scopeTypes: result.scopeTypes,reviewerEmail: result.reviewerEmail,diff --git a/frontend/editor/src/portal/components/pipelines/inputTriggerConfig.ts b/frontend/editor/src/portal/components/pipelines/inputTriggerConfig.tsnew file mode 100644index 0000000000..aaa59f7b76--- /dev/null+++ b/frontend/editor/src/portal/components/pipelines/inputTriggerConfig.ts@@ -0,0 +1,46 @@+import type { TriggerConfig } from "@portal/api/pipelines";+import {+ MANUAL,+ type ScheduleUnit,+ type WorkingInput,+} from "@portal/components/pipelines/PipelineInputTrigger";++export function parseTrigger(trigger: TriggerConfig | null): {+ triggerType: string;+ count: string;+ unit: ScheduleUnit;+} {+ if (!trigger) return { triggerType: MANUAL, count: "1", unit: "HOURS" };+ if (trigger.type === "schedule") {+ const schedule = trigger.options?.schedule as+ | { type?: string; count?: number; unit?: ScheduleUnit }+ | undefined;+ if (schedule?.type === "every") {+ return {+ triggerType: "schedule",+ count: String(schedule.count ?? 1),+ unit: schedule.unit ?? "HOURS",+ };+ }+ return { triggerType: "schedule", count: "1", unit: "HOURS" };+ }+ return { triggerType: trigger.type, count: "1", unit: "HOURS" };+}++/** The trigger config for the input row, or null for a manual (on-demand) input. */+export function buildTriggerFor(input: WorkingInput): TriggerConfig | null {+ if (input.triggerType === MANUAL) return null;+ if (input.triggerType === "schedule") {+ return {+ type: "schedule",+ options: {+ schedule: {+ type: "every",+ count: Number(input.scheduleCount),+ unit: input.scheduleUnit,+ },+ },+ };+ }+ return { type: input.triggerType, options: {} };+}diff --git a/frontend/editor/src/portal/components/policies/PolicySetupConnections.tsx b/frontend/editor/src/portal/components/policies/PolicySetupConnections.tsxnew file mode 100644index 0000000000..8106f563ad--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicySetupConnections.tsx@@ -0,0 +1,42 @@+import { useEffect, useState } from "react";+import type { PolicySetupConfigProps } from "@app/components/policies/PolicySetupWizard";+import { PolicySetupInput } from "@portal/components/policies/PolicySetupInput";+import { PolicySetupOutput } from "@portal/components/policies/PolicySetupOutput";++interface Props extends PolicySetupConfigProps {+ folderName?: string;+ readOnly?: boolean;+}++/** Combines input and output validation for the shared wizard draft. */+export function PolicySetupConnections({+ result,+ onChange,+ onValidityChange,+ folderName,+ readOnly = false,+}: Props) {+ const [inputValid, setInputValid] = useState(false);+ const [outputValid, setOutputValid] = useState(false);+ useEffect(+ () => onValidityChange(inputValid && outputValid),+ [inputValid, outputValid, onValidityChange],+ );++ return (+ <fieldset disabled={readOnly} className="portal-policies__setup-locations">+ <PolicySetupInput+ result={result}+ onChange={onChange}+ onValidityChange={setInputValid}+ folderName={folderName}+ />+ <PolicySetupOutput+ result={result}+ onChange={onChange}+ onValidityChange={setOutputValid}+ folderName={folderName}+ />+ </fieldset>+ );+}diff --git a/frontend/editor/src/portal/components/policies/PolicySetupFlows.test.tsx b/frontend/editor/src/portal/components/policies/PolicySetupFlows.test.tsxnew file mode 100644index 0000000000..5a8f0752ce--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicySetupFlows.test.tsx@@ -0,0 +1,486 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { PortalTestProviders } from "@portal/test/TestQueryProvider";+import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";+import {+ POLICY_CATEGORIES,+ POLICY_CONFIG,+ type CatalogueEntry,+} from "@portal/api/policies";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: unknown) =>+ typeof fallback === "string" ? fallback : key,+ i18n: { changeLanguage: vi.fn() },+ }),+ initReactI18next: { type: "3rdParty", init: vi.fn() },+}));+const api = vi.hoisted(() => ({+ capabilities: vi.fn(),+ sources: vi.fn(),+ source: vi.fn(),+}));+vi.mock("@portal/api/docparse", () => ({+ fetchDocparseCapabilities: api.capabilities,+}));+vi.mock("@portal/api/sources", async (original) => ({+ ...(await original<typeof import("@portal/api/sources")>()),+ fetchSources: api.sources,+ fetchSource: api.source,+}));+vi.mock("@portal/api/integrations", async (original) => ({+ ...(await original<typeof import("@portal/api/integrations")>()),+ fetchIntegrations: () => Promise.resolve([]),+}));+vi.mock("@portal/api/pipelines", async (original) => ({+ ...(await original<typeof import("@portal/api/pipelines")>()),+ fetchTriggers: () =>+ Promise.resolve([+ { type: "schedule", requiresSource: false, supportedSourceTypes: [] },+ ]),+}));++const category = POLICY_CATEGORIES.find((item) => item.id === "ingestion")!;+const entry: CatalogueEntry = {+ category,+ config: POLICY_CONFIG.ingestion,+ policy: null,+};+const enable = "portal.policies.wizard.actions.enablePolicy";++async function mount(current = entry) {+ const save = vi.fn().mockResolvedValue(undefined);+ const customise = vi.fn();+ render(+ <PolicySetupWizard+ entry={current}+ onClose={vi.fn()}+ onSubmit={save}+ onCustomise={customise}+ />,+ { wrapper: PortalTestProviders },+ );+ await waitFor(() =>+ expect(+ screen.queryByText("Checking ingestion availability..."),+ ).not.toBeInTheDocument(),+ );+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Close" })).toHaveFocus(),+ );+ return { save, customise };+}+async function select(label: string, option: string) {+ const input = screen.getByRole("textbox", { name: label });+ fireEvent.click(input);+ const list = document.getElementById(input.getAttribute("aria-controls")!);+ fireEvent.click(+ await within(list!).findByRole("option", { name: option, hidden: true }),+ );+}++beforeEach(() => {+ HTMLElement.prototype.scrollIntoView = vi.fn();+ api.capabilities.mockReset().mockResolvedValue({+ enabled: true,+ engineReachable: true,+ indexingConfigured: false,+ });+ api.sources.mockReset().mockResolvedValue({ sources: [], kpis: [] });+ api.source.mockReset().mockResolvedValue({+ id: "in",+ type: "folder",+ name: "Incoming PDFs",+ enabled: true,+ options: { mode: "track" },+ });+});++describe("guided ingestion flows", () => {+ it("requires a file destination to export without a database", async () => {+ api.sources.mockResolvedValue({+ sources: [+ { id: "in", type: "folder", name: "Incoming PDFs", status: "active" },+ {+ id: "files",+ type: "folder",+ name: "Exported files",+ status: "active",+ },+ ],+ kpis: [],+ });+ const { save } = await mount();+ await select("Input source", "Incoming PDFs");+ await select("Output type", "Export chunks without a database");+ expect(screen.getByRole("button", { name: enable })).toBeDisabled();+ await select("portal.pipelines.composer.output", "Exported files");+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ const result = save.mock.calls[0][1];+ expect(result.runsOnEditor).toBe(false);+ expect(result.required).toBe(false);+ expect(result.extraOptions ?? {}).not.toHaveProperty("ragDestination");+ expect(result.outputIds).toEqual(["files"]);+ expect(result.steps.at(-1).parameters).toMatchObject({+ index: false,+ includeOriginal: true,+ exportChunksJsonl: true,+ });+ });++ it.each([+ ["Export chunks without a database", "folder"],+ ["Connected vector database", "vectordb"],+ ])(+ "keeps editor input and requires a destination for %s",+ async (output, type) => {+ api.sources.mockResolvedValue({+ sources: [+ { id: "out", type, name: "Saved destination", status: "active" },+ ],+ kpis: [],+ });+ const { save } = await mount();+ await select("Input source", "Files opened in the editor");+ await select("Output type", output);+ expect(screen.getByRole("textbox", { name: "Delivery" })).toHaveValue(+ "Keep originals and send to a destination",+ );+ expect(+ screen.getByText(/Your editor files stay unchanged/),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: enable })).toBeDisabled();+ await select("portal.pipelines.composer.output", "Saved destination");+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ expect(save.mock.calls[0][1]).toMatchObject({+ runsOnEditor: true,+ inputs: [],+ outputIds: ["out"],+ });+ expect(save.mock.calls[0][1].steps.at(-1).parameters).toMatchObject({+ index: false,+ exportChunksJsonl: true,+ });+ },+ );++ it("preserves a selected destination when switching the input to editor", async () => {+ api.sources.mockResolvedValue({+ sources: [+ { id: "in", type: "folder", name: "Incoming PDFs", status: "active" },+ {+ id: "out",+ type: "folder",+ name: "Saved destination",+ status: "active",+ },+ ],+ kpis: [],+ });+ const { save } = await mount();+ await select("Input source", "Incoming PDFs");+ await select("Output type", "Export chunks without a database");+ await select("portal.pipelines.composer.output", "Saved destination");+ await select("Input source", "Files opened in the editor");+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ expect(save.mock.calls[0][1]).toMatchObject({+ runsOnEditor: true,+ outputIds: ["out"],+ });+ });++ it.each(["exportChunksJsonl", "exportMarkdown"])(+ "requires a destination for a legacy editor policy with %s",+ async (flag) => {+ api.capabilities.mockResolvedValue({+ enabled: true,+ engineReachable: true,+ indexingConfigured: true,+ });+ api.sources.mockResolvedValue({+ sources: [+ { id: "archive", name: "Archive", type: "folder", status: "active" },+ ],+ kpis: [],+ });+ const current: CatalogueEntry = {+ ...entry,+ policy: {+ category,+ config: POLICY_CONFIG.ingestion,+ state: {+ configured: true,+ status: "paused",+ required: false,+ sources: ["editor"],+ scopeTypes: [],+ reviewerEmail: "",+ fieldValues: {},+ runOn: "upload",+ outputMode: "new_version",+ outputName: "",+ outputNamePosition: "suffix",+ maxRetries: 0,+ retryDelayMinutes: 0,+ backendId: "legacy",+ isDefault: false,+ runsOnEditor: true,+ extraOptions: { ragDestination: "builtin" },+ },+ steps: [+ {+ operation: "/api/v1/docparse/ingest",+ parameters: { index: true, [flag]: true },+ },+ ],+ stats: { enforced: 0, dataProcessed: "-", activeFor: "-" },+ activity: [],+ },+ };+ const { save } = await mount(current);+ const saveLabel = "portal.policies.wizard.actions.saveChanges";+ expect(+ await screen.findByText(/Choose an enabled output destination/),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: saveLabel })).toBeDisabled();+ await select("portal.pipelines.composer.output", "Archive");+ await waitFor(() =>+ expect(screen.getByRole("button", { name: saveLabel })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: saveLabel }));+ expect(save.mock.calls[0][1].outputIds).toEqual(["archive"]);+ expect(save.mock.calls[0][1].steps.at(-1).parameters).toMatchObject({+ index: true,+ [flag]: true,+ });+ },+ );++ it("saves actual input and database IDs with chunks-only output", async () => {+ api.sources.mockResolvedValue({+ sources: [+ { id: "in", type: "folder", name: "Incoming PDFs", status: "active" },+ {+ id: "out",+ type: "vectordb",+ name: "Research database",+ status: "unused",+ },+ ],+ kpis: [],+ });+ const { save } = await mount();+ await waitFor(() => expect(api.sources).toHaveBeenCalled());+ await select("Input source", "Incoming PDFs");+ await select("Output type", "Connected vector database");+ await select("portal.pipelines.composer.output", "Research database");+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ expect(save.mock.calls[0][1]).toMatchObject({+ inputs: [{ sourceId: "in", trigger: null }],+ outputIds: ["out"],+ runsOnEditor: false,+ });+ expect(save.mock.calls[0][1].steps.at(-1).parameters).toMatchObject({+ index: false,+ includeOriginal: false,+ exportMarkdown: false,+ exportChunksJsonl: true,+ });+ });++ it("blocks indexing while the engine is unavailable but permits OCR only", async () => {+ api.capabilities.mockResolvedValue({+ enabled: false,+ engineReachable: false,+ });+ const { save } = await mount();+ await select("Input source", "Files opened in the editor");+ expect(+ await screen.findByText(/engine is disabled or unreachable/),+ ).toBeTruthy();+ expect(screen.getByRole("button", { name: enable })).toBeDisabled();+ fireEvent.click(+ screen.getByRole("switch", { name: "Prepare for knowledge search" }),+ );+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ expect(save.mock.calls[0][1].steps).toHaveLength(1);+ expect(save.mock.calls[0][1].steps[0].operation).toBe(+ "/api/v1/misc/ocr-pdf",+ );+ });++ it("rechecks readiness after configuration without losing the policy draft", async () => {+ const { save } = await mount();+ await select("Input source", "Files opened in the editor");+ await screen.findByText(+ /built-in knowledge base needs an embedding provider/,+ );+ api.capabilities.mockResolvedValue({+ enabled: true,+ engineReachable: true,+ indexingConfigured: true,+ });+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ expect(save.mock.calls[0][1].steps.at(-1).parameters.index).toBe(true);+ expect(save.mock.calls[0][1].runsOnEditor).toBe(true);+ });++ it("reports failed saves in the open wizard and allows retry", async () => {+ api.capabilities.mockResolvedValue({+ enabled: true,+ engineReachable: true,+ indexingConfigured: true,+ });+ const { save } = await mount();+ save.mockRejectedValueOnce(+ new Error("The selected connection was removed"),+ );+ await select("Input source", "Files opened in the editor");+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ expect(+ await screen.findByText("The selected connection was removed"),+ ).toBeTruthy();+ expect(screen.getByRole("alert")).toHaveFocus();+ expect(screen.getByRole("button", { name: enable })).toBeEnabled();+ });+ it("keeps invalid chunk edits visible and saves corrected values", async () => {+ api.capabilities.mockResolvedValue({+ enabled: true,+ engineReachable: true,+ indexingConfigured: true,+ });+ const { save } = await mount();+ await select("Input source", "Files opened in the editor");+ fireEvent.click(screen.getByRole("button", { name: "Chunk settings" }));+ const overlap = screen.getByRole("spinbutton", {+ name: "portal.pipelines.builder.ingest.overlap",+ });+ fireEvent.change(overlap, { target: { value: "1024" } });+ expect(overlap).toHaveValue(1024);+ expect(screen.getByRole("button", { name: enable })).toBeDisabled();+ fireEvent.change(overlap, { target: { value: "128" } });+ await waitFor(() =>+ expect(screen.getByRole("button", { name: enable })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: enable }));+ expect(save.mock.calls[0][1].steps.at(-1).parameters.overlap).toBe(128);+ });+ it("reopens the actual database destination despite stale wizard metadata and preserves step settings", async () => {+ api.sources.mockResolvedValue({+ sources: [+ {+ id: "db",+ type: "vectordb",+ name: "Saved database",+ status: "active",+ },+ ],+ kpis: [],+ });+ const current: CatalogueEntry = {+ ...entry,+ policy: {+ category,+ config: POLICY_CONFIG.ingestion,+ state: {+ configured: true,+ status: "paused",+ required: true,+ sources: [],+ scopeTypes: [],+ reviewerEmail: "",+ fieldValues: {},+ runOn: "export",+ outputMode: "new_version",+ outputName: "",+ outputNamePosition: "suffix",+ maxRetries: 0,+ retryDelayMinutes: 0,+ backendId: "edited",+ isDefault: false,+ runsOnEditor: true,+ outputIds: ["db"],+ extraOptions: {+ ragDestination: "builtin",+ editorDelivery: "workspace",+ automation: { name: "keep" },+ },+ },+ steps: [+ {+ operation: "/api/v1/docparse/ingest",+ parameters: {+ index: false,+ includeOriginal: false,+ exportChunksJsonl: true,+ overlap: 0,+ documentId: "pinned-document",+ futureOption: "keep",+ },+ fileParameters: { supportingFile: "saved-asset" },+ },+ ],+ stats: { enforced: 0, dataProcessed: "-", activeFor: "-" },+ activity: [],+ },+ };+ const { save, customise } = await mount(current);+ expect(screen.getByRole("textbox", { name: "Output type" })).toHaveValue(+ "Connected vector database",+ );+ expect(+ screen.queryByRole("switch", { name: "portal.pipelines.enforce.label" }),+ ).not.toBeInTheDocument();+ const saveLabel = "portal.policies.wizard.actions.saveChanges";+ await waitFor(() =>+ expect(screen.getByRole("button", { name: saveLabel })).toBeEnabled(),+ );+ fireEvent.click(screen.getByRole("button", { name: /customise/i }));+ const draft = customise.mock.calls[0][1];+ expect(draft.required).toBe(false);+ expect(draft.steps[0]).toMatchObject({+ parameters: {+ overlap: 0,+ documentId: "pinned-document",+ futureOption: "keep",+ },+ fileParameters: { supportingFile: "saved-asset" },+ });+ fireEvent.click(screen.getByRole("button", { name: saveLabel }));+ expect(save.mock.calls[0][1]).toMatchObject({+ outputIds: ["db"],+ required: false,+ runOn: "export",+ steps: draft.steps,+ });+ });+});diff --git a/frontend/editor/src/portal/components/policies/PolicySetupInput.tsx b/frontend/editor/src/portal/components/policies/PolicySetupInput.tsxnew file mode 100644index 0000000000..bcb61a10db--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicySetupInput.tsx@@ -0,0 +1,249 @@+import { useEffect, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { Banner, Button, FormField, Select } from "@app/ui";+import type { PolicySetupConfigProps } from "@app/components/policies/PolicySetupWizard";+import { fetchSources, fetchSource } from "@portal/api/sources";+import { fetchTriggers } from "@portal/api/pipelines";+import { errorMessage } from "@portal/api/http";+import { qk } from "@portal/queries/keys";+import {+ PipelineInputTrigger,+ type WorkingInput,+} from "@portal/components/pipelines/PipelineInputTrigger";+import {+ buildTriggerFor,+ parseTrigger,+} from "@portal/components/pipelines/inputTriggerConfig";+import { SourceModal } from "@portal/components/sources/SourceModal";+import {+ EDITOR_SOURCE_TYPE,+ isReadableSource,+} from "@portal/components/sources/sourceTypes";++interface Props extends PolicySetupConfigProps {+ folderName?: string;+}+const RETAIN_OPTIONS = { mode: "track" };++/** Owns source selection, trigger configuration, and input validity. */+export function PolicySetupInput({+ result,+ onChange,+ onValidityChange,+ folderName,+}: Props) {+ const { t } = useTranslation();+ const queryClient = useQueryClient();+ const [sourceModal, setSourceModal] = useState<{ id?: string } | null>(null);+ const sources = useQuery({ queryKey: qk.sources(), queryFn: fetchSources });+ const triggers = useQuery({+ queryKey: ["policy-setup-triggers"],+ queryFn: fetchTriggers,+ enabled: !folderName,+ });+ const editor = !folderName && result.runsOnEditor;+ const input = result.inputs?.[0];+ const selectedInput = useQuery({+ queryKey: ["policy-setup-source", input?.sourceId],+ queryFn: () => fetchSource(input!.sourceId),+ enabled: Boolean(input?.sourceId) && !result.runsOnEditor && !folderName,+ });+ const allSources = sources.data?.sources ?? [];+ const availableSources = allSources.filter(+ (source) => isReadableSource(source) && source.type !== EDITOR_SOURCE_TYPE,+ );+ const parsed = parseTrigger(input?.trigger ?? null);+ const workingInput: WorkingInput = {+ sourceId: input?.sourceId ?? "",+ triggerType: parsed.triggerType,+ scheduleCount: parsed.count,+ scheduleUnit: parsed.unit,+ };+ const triggerOptions = [+ {+ value: "manual",+ label: t("portal.pipelines.composer.triggerManual", "On demand"),+ },+ ...(triggers.data ?? [])+ .filter(+ (trigger) =>+ !trigger.requiresSource ||+ trigger.supportedSourceTypes.includes(selectedInput.data?.type ?? ""),+ )+ .map((trigger) => ({+ value: trigger.type,+ label: t(`portal.pipelines.trigger.${trigger.type}`, trigger.type),+ })),+ ];+ const inputReady =+ Boolean(folderName) ||+ editor ||+ Boolean(+ input?.sourceId &&+ selectedInput.data?.enabled &&+ !selectedInput.isFetching &&+ !selectedInput.error,+ );+ const scheduleReady =+ workingInput.triggerType !== "schedule" ||+ (Number.isInteger(Number(workingInput.scheduleCount)) &&+ Number(workingInput.scheduleCount) > 0);+ const valid = inputReady && scheduleReady;+ useEffect(() => onValidityChange(valid), [valid, onValidityChange]);+ function selectInput(id: string | null) {+ onChange({+ runsOnEditor: id === "editor",+ inputs: id && id !== "editor" ? [{ sourceId: id, trigger: null }] : [],+ });+ }++ return (+ <>+ <div className="portal-policies__wizard-section">+ <h3 className="portal-policies__wizard-heading">+ {t("portal.policies.wizard.locations.input", "Documents to process")}+ </h3>+ {folderName ? (+ <p className="portal-policies__wizard-desc">+ {t(+ "portal.policies.wizard.locations.folder",+ "Input: {{name}}. Originals are retained when delivering to a vector database.",+ { name: folderName },+ )}+ </p>+ ) : (+ <>+ <FormField+ label={t(+ "portal.policies.wizard.locations.source",+ "Input source",+ )}+ >+ <Select+ inputSize="sm"+ aria-label={t(+ "portal.policies.wizard.locations.source",+ "Input source",+ )}+ value={editor ? "editor" : (input?.sourceId ?? null)}+ placeholder={t(+ "portal.policies.wizard.locations.chooseSource",+ "Choose where documents come from",+ )}+ onChange={selectInput}+ options={[+ {+ value: "editor",+ label: t(+ "portal.policies.wizard.locations.editor",+ "Files opened in the editor",+ ),+ },+ ...availableSources.map((source) => ({+ value: source.id,+ label: source.name,+ })),+ ]}+ />+ </FormField>+ <PipelineInputTrigger+ input={workingInput}+ onInputChange={(patch) =>+ onChange({+ inputs: [+ {+ sourceId: workingInput.sourceId,+ trigger: buildTriggerFor({ ...workingInput, ...patch }),+ },+ ],+ })+ }+ triggerOptions={triggerOptions}+ isEditorInput={editor}+ runOn={result.runOn}+ onRunOnChange={(runOn) => onChange({ runOn })}+ />+ <div className="portal-policies__setup-actions">+ <Button+ size="sm"+ variant="tertiary"+ onClick={() => setSourceModal({})}+ >+ {t(+ "portal.policies.wizard.locations.connectInput",+ "Connect input source",+ )}+ </Button>+ {input?.sourceId && (+ <Button+ size="sm"+ variant="tertiary"+ onClick={() => setSourceModal({ id: input.sourceId })}+ >+ {t(+ "portal.policies.wizard.locations.editInput",+ "Edit input source",+ )}+ </Button>+ )}+ </div>+ {selectedInput.data &&+ ["folder", "s3", "sftp", "ftp", "network"].includes(+ selectedInput.data.type,+ ) && (+ <Banner+ tone={+ selectedInput.data.options.mode === "consume" ||+ !selectedInput.data.options.mode+ ? "warning"+ : "info"+ }+ description={+ selectedInput.data.options.mode === "track" ||+ selectedInput.data.options.mode === "snapshot"+ ? t(+ "portal.policies.wizard.locations.retained",+ "This source does not delete inputs after processing. Choose a separate destination to keep the original files unchanged.",+ )+ : t(+ "portal.policies.wizard.locations.consumed",+ "Check this source's processing mode: consume deletes originals after a successful run. Choose Track in Edit input source to keep them.",+ )+ }+ />+ )}+ </>+ )}+ {!folderName &&+ !editor &&+ (sources.error || selectedInput.error || triggers.error) && (+ <Banner+ tone="danger"+ description={errorMessage(+ sources.error ?? selectedInput.error ?? triggers.error,+ )}+ />+ )}+ </div>++ {sourceModal && (+ <SourceModal+ open+ direction="input"+ sourceId={sourceModal.id}+ initialOptions={RETAIN_OPTIONS}+ onClose={() => setSourceModal(null)}+ onCreated={(source) => {+ if (source.id) selectInput(source.id);+ }}+ onSaved={() => {+ void queryClient.invalidateQueries({+ queryKey: ["policy-setup-source"],+ });+ }}+ />+ )}+ </>+ );+}diff --git a/frontend/editor/src/portal/components/policies/PolicySetupOutput.tsx b/frontend/editor/src/portal/components/policies/PolicySetupOutput.tsxnew file mode 100644index 0000000000..487aefb67c--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicySetupOutput.tsx@@ -0,0 +1,205 @@+import { useEffect, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { Banner, Button, FormField, Input } from "@app/ui";+import type { PolicySetupConfigProps } from "@app/components/policies/PolicySetupWizard";+import { PolicyIngestionConfig } from "@app/components/policies/PolicyIngestionConfig";+import { EditorDeliverySelect } from "@portal/components/pipelines/EditorDeliverySelect";+import { DestinationPicker } from "@portal/components/pipelines/DestinationPicker";+import { availableOutputModes } from "@portal/components/pipelines/outputModes";+import { SourceModal } from "@portal/components/sources/SourceModal";+import { fetchSources } from "@portal/api/sources";+import { errorMessage } from "@portal/api/http";+import { qk } from "@portal/queries/keys";+import { usePolicySetupIngestion } from "@portal/components/policies/usePolicySetupIngestion";++interface Props extends PolicySetupConfigProps {+ folderName?: string;+}+const VECTOR_TYPES = ["vectordb"];++/** Owns output selection and its ingestion and editor-delivery constraints. */+export function PolicySetupOutput({+ result,+ onChange,+ onValidityChange,+ folderName,+}: Props) {+ const { t } = useTranslation();+ const queryClient = useQueryClient();+ const [sourceModal, setSourceModal] = useState<{ id?: string } | null>(null);+ const sources = useQuery({ queryKey: qk.sources(), queryFn: fetchSources });+ const allSources = sources.data?.sources ?? [];+ const destination = allSources.find(+ (source) => source.id === result.outputIds?.[0],+ );+ const ingestion = usePolicySetupIngestion({+ result,+ onChange,+ folderName,+ destinationType: destination?.type,+ });+ const { external, requiresDestination } = ingestion;+ const editor = !folderName && result.runsOnEditor;+ const [destinationRequested, setDestinationRequested] = useState(false);+ const externalEditorOutput =+ editor &&+ (requiresDestination ||+ Boolean(result.outputIds?.length) ||+ destinationRequested);+ const outputSources = allSources.filter(+ (source) =>+ (availableOutputModes() as string[]).includes(source.type) &&+ (external ? source.type === "vectordb" : source.type !== "vectordb"),+ );+ const outputNeeded =+ externalEditorOutput ||+ (!editor && (!folderName || external || Boolean(result.outputIds?.length)));+ const outputReady =+ !outputNeeded ||+ (result.outputIds?.length === 1 &&+ outputSources.some(+ (source) =>+ source.id === result.outputIds?.[0] && source.status !== "disabled",+ ));+ const valid = outputReady && ingestion.valid;+ useEffect(() => onValidityChange(valid), [valid, onValidityChange]);+ const destinationPicker =+ editor && !externalEditorOutput ? (+ <FormField+ label={t("portal.policies.wizard.locations.destination", "Destination")}+ helperText={t(+ "portal.policies.wizard.locations.editorOutput",+ "Processed PDFs return to the editor workspace.",+ )}+ >+ <Input+ inputSize="sm"+ value={t(+ "portal.policies.wizard.locations.editorDestination",+ "Editor workspace",+ )}+ readOnly+ />+ </FormField>+ ) : folderName && !external && !result.outputIds?.length ? (+ <FormField+ label={t("portal.policies.wizard.locations.destination", "Destination")}+ helperText={t(+ "portal.policies.wizard.locations.folderOutput",+ "Processed files are saved in this folder. Corpus exports keep the original PDF.",+ )}+ >+ <Input inputSize="sm" value={folderName} readOnly />+ </FormField>+ ) : (+ <>+ {external &&+ outputSources.length === 0 &&+ !sources.isPending &&+ !sources.error && (+ <Banner+ tone="info"+ description={t(+ "portal.policies.wizard.locations.noDatabase",+ "No vector database destination is set up. Connect a source below, then choose or create its database connection and collection.",+ )}+ />+ )}+ {sources.error && (+ <>+ <Banner tone="danger" description={errorMessage(sources.error)} />+ <Button+ size="sm"+ variant="tertiary"+ onClick={() => void sources.refetch()}+ >+ {t("common.retry", "Retry")}+ </Button>+ </>+ )}+ <DestinationPicker+ sources={outputSources}+ value={result.outputIds ?? []}+ onChange={(outputIds) => onChange({ outputIds })}+ onCreateNew={() => setSourceModal({})}+ onEdit={(id) => setSourceModal({ id })}+ />+ {!outputReady && (+ <p className="portal-policies__wizard-desc">+ {t(+ "portal.policies.wizard.locations.chooseOutput",+ "Choose an enabled output destination before saving.",+ )}+ </p>+ )}+ {folderName && !external && (+ <Button+ size="sm"+ variant="tertiary"+ onClick={() => onChange({ outputIds: [] })}+ >+ {t(+ "portal.policies.wizard.locations.returnToFolder",+ "Return results to this folder",+ )}+ </Button>+ )}+ </>+ );++ const outputDestination = (+ <>+ {editor && (+ <EditorDeliverySelect+ external={externalEditorOutput}+ requiresDestination={requiresDestination}+ onChange={(external) => {+ setDestinationRequested(external);+ if (!external) onChange({ outputIds: [] });+ }}+ />+ )}+ {destinationPicker}+ </>+ );++ return (+ <section+ className="portal-policies__wizard-section"+ aria-label={t("portal.policies.wizard.locations.output", "Output")}+ >+ <h3 className="portal-policies__wizard-heading">+ {t("portal.policies.wizard.locations.output", "Output")}+ </h3>+ {ingestion.config ? (+ <PolicyIngestionConfig {...ingestion.config}>+ {outputDestination}+ </PolicyIngestionConfig>+ ) : (+ outputDestination+ )}+ {sourceModal && (+ <SourceModal+ open+ direction="output"+ sourceId={sourceModal.id}+ allowedTypes={+ external+ ? VECTOR_TYPES+ : availableOutputModes().filter((type) => type !== "vectordb")+ }+ onClose={() => setSourceModal(null)}+ onCreated={(source) => {+ if (source.id) onChange({ outputIds: [source.id] });+ }}+ onSaved={() => {+ void queryClient.invalidateQueries({+ queryKey: ["policy-setup-source"],+ });+ }}+ />+ )}+ </section>+ );+}diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsxindex 808dbdf268..00ce29192e 100644--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx@@ -9,6 +9,7 @@ import { fetchIntegrations } from "@portal/api/integrations";import { errorMessage } from "@portal/api/http";import { useAsync } from "@portal/hooks/useAsync";import { useMemo } from "react";+import { PolicySetupConnections } from "@portal/components/policies/PolicySetupConnections";import { PolicyPurviewConfig } from "@portal/components/policies/PolicyPurviewConfig";import { PolicyRoutingConfig } from "@portal/components/policies/PolicyRoutingConfig";@@ -40,6 +41,12 @@ export function PolicySetupWizard(props: PolicySetupWizardProps) {{...props}hasPurviewConnection={hasPurviewConnection}formatError={errorMessage}+ setupConfig={(config) => (+ <PolicySetupConnections+ {...config}+ readOnly={props.canManagePolicies === false}+ />+ )}purviewConfig={({ parameters, onChange }) => (<PolicyPurviewConfig parameters={parameters} onChange={onChange} />)}diff --git a/frontend/editor/src/portal/components/policies/usePolicySetupIngestion.ts b/frontend/editor/src/portal/components/policies/usePolicySetupIngestion.tsnew file mode 100644index 0000000000..68124c9b1e--- /dev/null+++ b/frontend/editor/src/portal/components/policies/usePolicySetupIngestion.ts@@ -0,0 +1,124 @@+import { useState, type ComponentProps } from "react";+import { useQuery } from "@tanstack/react-query";+import type { PolicySetupConfigProps } from "@app/components/policies/PolicySetupWizard";+import type {+ PolicyIngestionConfig,+ IngestionDestination,+} from "@app/components/policies/PolicyIngestionConfig";+import { ingestChunkingConfigured } from "@app/policies/ingestOperation";+import { policyStepFromWire, policyStepToWire } from "@app/policies/operations";+import { fetchDocparseCapabilities } from "@portal/api/docparse";++interface Props extends Pick<PolicySetupConfigProps, "result" | "onChange"> {+ folderName?: string;+ destinationType?: string;+}++/** Keeps incomplete chunk edits local while reporting executable ingestion settings. */+export function usePolicySetupIngestion({+ result,+ onChange,+ folderName,+ destinationType,+}: Props) {+ const ingestion = result.steps+ .map(policyStepFromWire)+ .find((step) => step?.toolId === "ingest");+ const capabilities = useQuery({+ queryKey: ["policy-setup-docparse"],+ queryFn: () => fetchDocparseCapabilities(),+ enabled: Boolean(ingestion),+ staleTime: 0,+ retry: false,+ });+ const [chunkDraft, setChunkDraft] = useState<Record<string, string>>({});+ const ingestionParameters = ingestion+ ? { ...ingestion.params, ...chunkDraft }+ : null;+ const [targetDraft, setTargetDraft] = useState<IngestionDestination>();+ const target: IngestionDestination =+ targetDraft ??+ (destinationType === "vectordb" ||+ (folderName && Boolean(result.outputIds?.length))+ ? "external"+ : ingestion?.params.index === "false"+ ? "export"+ : "builtin");+ const external = Boolean(ingestion) && target === "external";+ const requiresDestination =+ Boolean(ingestion) &&+ (target !== "builtin" ||+ ingestion?.params.exportChunksJsonl === "true" ||+ ingestion?.params.exportMarkdown === "true" ||+ ingestion?.params.includeOriginal === "false");+ const engineReady =+ capabilities.data?.enabled && capabilities.data.engineReachable;+ const indexingReady = capabilities.data?.indexingConfigured === true;+ const chunkingReady =+ !ingestion ||+ ingestChunkingConfigured({+ chunkSize: Number(ingestionParameters?.chunkSize),+ overlap: Number(ingestionParameters?.overlap),+ });+ const valid =+ chunkingReady &&+ (!ingestion ||+ Boolean(+ engineReady &&+ !capabilities.isFetching &&+ (ingestion.params.index === "false" || indexingReady),+ ));+ function changeTarget(next: IngestionDestination) {+ if (!ingestion) return;+ setChunkDraft({});+ setTargetDraft(next);+ onChange({+ outputIds:+ next === "external" || target === "external" ? [] : result.outputIds,+ steps: result.steps.map((wire) =>+ wire.operation === policyStepToWire(ingestion).operation+ ? policyStepToWire({+ ...ingestion,+ params: {+ ...ingestion.params,+ index: String(next === "builtin"),+ includeOriginal: String(next !== "external"),+ exportMarkdown: "false",+ exportChunksJsonl: String(next !== "builtin"),+ },+ })+ : wire,+ ),+ });+ }++ function updateChunk(key: "chunkSize" | "overlap", value: string) {+ if (!ingestion) return;+ setChunkDraft({ ...chunkDraft, [key]: value });+ onChange({+ steps: result.steps.map((wire) =>+ wire.operation === policyStepToWire(ingestion).operation+ ? policyStepToWire({+ ...ingestion,+ params: { ...ingestion.params, ...chunkDraft, [key]: value },+ })+ : wire,+ ),+ });+ }++ const config: ComponentProps<typeof PolicyIngestionConfig> | null = ingestion+ ? {+ parameters: { ...ingestion.params, ...chunkDraft },+ target,+ onTargetChange: changeTarget,+ onChange: updateChunk,+ engineReady: Boolean(engineReady),+ indexingReady,+ chunkingReady,+ checking: capabilities.isFetching,+ recheck: () => void capabilities.refetch(),+ }+ : null;+ return { config, external, requiresDestination, valid };+}diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsxindex 44a9055b2a..918a69d534 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx@@ -1,4 +1,8 @@import { EditorDeliverySelect } from "@portal/components/pipelines/EditorDeliverySelect";+import {+ parseTrigger,+ buildTriggerFor,+} from "@portal/components/pipelines/inputTriggerConfig";import { requiresClassification } from "@app/data/classificationConditions";import { isConditionComplete } from "@app/conditions/validation";import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";@@ -58,7 +62,6 @@ import {type PolicyRunView,type RunOutputFile,type TestRunAsset,- type TriggerConfig,type TriggerInfo,type TriggerOutcome,} from "@portal/api/pipelines";@@ -123,7 +126,6 @@ import {MANUAL_OPTION,PipelineInputTrigger,type EditorRunOn,- type ScheduleUnit,type WorkingInput,} from "@portal/components/pipelines/PipelineInputTrigger";import "@portal/views/PipelineBuilder.css";@@ -138,28 +140,6 @@ type RunResult = {text: string;};-function parseTrigger(trigger: TriggerConfig | null): {- triggerType: string;- count: string;- unit: ScheduleUnit;-} {- if (!trigger) return { triggerType: MANUAL, count: "1", unit: "HOURS" };- if (trigger.type === "schedule") {- const schedule = trigger.options?.schedule as- | { type?: string; count?: number; unit?: ScheduleUnit }- | undefined;- if (schedule?.type === "every") {- return {- triggerType: "schedule",- count: String(schedule.count ?? 1),- unit: schedule.unit ?? "HOURS",- };- }- return { triggerType: "schedule", count: "1", unit: "HOURS" };- }- return { triggerType: trigger.type, count: "1", unit: "HOURS" };-}-/** The input row with nothing chosen yet: no source, manual trigger. */function blankInput(): WorkingInput {return {@@ -170,24 +150,6 @@ function blankInput(): WorkingInput {};}-/** The trigger config for the input row, or null for a manual (on-demand) input. */-function buildTriggerFor(input: WorkingInput): TriggerConfig | null {- if (input.triggerType === MANUAL) return null;- if (input.triggerType === "schedule") {- return {- type: "schedule",- options: {- schedule: {- type: "every",- count: Number(input.scheduleCount),- unit: input.scheduleUnit,- },- },- };- }- return { type: input.triggerType, options: {} };-}-/*** Routing reads the verdict this step writes, so a rule is only offered once the pipeline has one.* Mirrors ClassificationStepPlanner.CLASSIFY_ENDPOINT.@@ -197,14 +159,12 @@ const CLASSIFY_OPERATION = "/api/v1/ai/tools/classify-and-label";function isClassifyStep(step: WorkingToolStep): boolean {return step.operation === CLASSIFY_OPERATION;}-function isClassifyTool(tool: ExecutableTool): boolean {return (tool.endpoint === CLASSIFY_OPERATION ||tool.endpoints?.includes(CLASSIFY_OPERATION) === true);}-/** Whether a source can be written to, i.e. offered as a pipeline destination. */function isWritableSource(source: { type: string }): boolean {return (availableOutputModes() as string[]).includes(source.type);diff --git a/frontend/editor/src/portal/views/Pipelines.test.tsx b/frontend/editor/src/portal/views/Pipelines.test.tsxindex 9392ac25a1..6bd9a4469a 100644--- a/frontend/editor/src/portal/views/Pipelines.test.tsx+++ b/frontend/editor/src/portal/views/Pipelines.test.tsx@@ -45,6 +45,7 @@ const fetchPipelines = vi.fn();const fetchPipeline = vi.fn();const fetchPolicyPermissions = vi.fn();vi.mock("@portal/api/pipelines", () => ({+ fetchTriggers: () => Promise.resolve([]),fetchPipelines: () => fetchPipelines(),fetchPipeline: (id: string) => fetchPipeline(id),fetchPolicyPermissions: () => fetchPolicyPermissions(),diff --git a/frontend/editor/src/portal/views/Pipelines.tsx b/frontend/editor/src/portal/views/Pipelines.tsxindex 67635882df..c61cc7517e 100644--- a/frontend/editor/src/portal/views/Pipelines.tsx+++ b/frontend/editor/src/portal/views/Pipelines.tsx@@ -98,8 +98,6 @@ export function Pipelines() {const connectSource = () =>navigate(`${toPortalPath(VIEW_PATHS.sources)}/new`);- // Open a suggested template in the simple wizard (a fresh policy). AI-gated templates stay closed- // until the engine is confirmed on, so a click during the app-config load can't open a disabled one.const openTemplate = useCallback((entry: CatalogueEntry) => {if (entry.category.comingSoon) return;@@ -149,12 +147,10 @@ export function Pipelines() {icon: stored?.icon,enabled: stored ? stored.status !== "paused" : wire.enabled,required: wire.required,- inputs: [],+ inputs: wire.inputs ?? [],steps: wire.steps,output: { type: wire.output.type, options: wire.output.options },- outputIds: [],- // A wizard policy only ever runs on the editor, so hand its editor participation to the- // builder rather than letting it default to disabled.+ outputIds: wire.outputIds ?? [],editor: wire.editor,};return draft;@@ -172,6 +168,7 @@ export function Pipelines() {refetch();} catch (e) {setPageError(errorMessage(e));+ throw e;}}diff --git a/frontend/editor/src/proprietary/components/policies/FolderIngestionSettings.tsx b/frontend/editor/src/proprietary/components/policies/FolderIngestionSettings.tsxnew file mode 100644index 0000000000..d2c50077ad--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/FolderIngestionSettings.tsx@@ -0,0 +1,184 @@+import { useEffect, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { Button, FormField, Input } from "@app/ui";+import apiClient from "@app/services/apiClient";+import type { PolicySetupConfigProps } from "@app/components/policies/PolicySetupWizard";+import {+ PolicyIngestionConfig,+ type IngestionDestination,+} from "@app/components/policies/PolicyIngestionConfig";+import { ingestChunkingConfigured } from "@app/policies/ingestOperation";+import { policyStepFromWire } from "@app/policies/operations";++/** Folder ingestion settings for surfaces without Processor connection management. */+export function FolderIngestionSettings({+ result,+ onChange,+ onValidityChange,+ folderName,+}: PolicySetupConfigProps & { folderName: string }) {+ const { t } = useTranslation();+ const ingestion = result.steps+ .map(policyStepFromWire)+ .find((step) => step?.toolId === "ingest");+ const [draft, setDraft] = useState<Record<string, string>>({});+ const parameters = ingestion ? { ...ingestion.params, ...draft } : null;+ const target: IngestionDestination = result.outputIds?.length+ ? "external"+ : ingestion?.params.index === "false"+ ? "export"+ : "builtin";+ const capabilities = useQuery({+ queryKey: ["folder-policy-docparse"],+ queryFn: async () =>+ (+ await apiClient.get<{+ enabled: boolean;+ engineReachable: boolean;+ indexingConfigured?: boolean;+ }>("/api/v1/docparse/capabilities")+ ).data,+ enabled: Boolean(ingestion),+ retry: false,+ staleTime: 0,+ });+ const engineReady = Boolean(+ capabilities.data?.enabled && capabilities.data.engineReachable,+ );+ const indexingReady = capabilities.data?.indexingConfigured === true;+ const chunkingReady =+ !ingestion ||+ ingestChunkingConfigured({+ chunkSize: Number(parameters?.chunkSize),+ overlap: Number(parameters?.overlap),+ });+ const valid =+ (!ingestion && target !== "external") ||+ (Boolean(ingestion) &&+ engineReady &&+ !capabilities.isFetching &&+ chunkingReady &&+ (ingestion?.params.index === "false" || indexingReady));+ useEffect(() => onValidityChange(valid), [valid, onValidityChange]);+ function patchIngestion(+ patch: Record<string, unknown>,+ next?: IngestionDestination,+ ) {+ onChange({+ ...(next+ ? {+ outputIds: [],+ }+ : {}),+ steps: result.steps.map((step) =>+ step.operation === "/api/v1/docparse/ingest"+ ? { ...step, parameters: { ...step.parameters, ...patch } }+ : step,+ ),+ });+ }+ const outputDestination =+ target === "external" ? (+ <>+ <FormField+ label={t(+ "portal.policies.wizard.locations.destination",+ "Destination",+ )}+ helperText={t(+ "portal.policies.wizard.locations.desktopExternal",+ "Manage this database connection in the web app’s Processor, or change the output type to return results to this folder.",+ )}+ >+ <Input+ inputSize="sm"+ value={t(+ "portal.policies.wizard.locations.savedDatabase",+ "Saved vector database",+ )}+ readOnly+ />+ </FormField>+ <Button+ size="sm"+ variant="tertiary"+ onClick={() =>+ onChange({+ outputIds: [],+ })+ }+ >+ {t(+ "portal.policies.wizard.locations.returnToFolder",+ "Return results to this folder",+ )}+ </Button>+ </>+ ) : (+ <FormField+ label={t("portal.policies.wizard.locations.destination", "Destination")}+ helperText={t(+ "portal.policies.wizard.locations.folderOutput",+ "Processed files are saved in this folder. Corpus exports keep the original PDF.",+ )}+ >+ <Input inputSize="sm" value={folderName} readOnly />+ </FormField>+ );++ return (+ <>+ <p className="portal-policies__wizard-desc">+ {t(+ "portal.policies.wizard.locations.folder",+ "Input: {{name}}. Originals are retained when delivering to a vector database.",+ { name: folderName },+ )}+ </p>+ <section+ className="portal-policies__wizard-section"+ aria-label={t("portal.policies.wizard.locations.output", "Output")}+ >+ <h3 className="portal-policies__wizard-heading">+ {t("portal.policies.wizard.locations.output", "Output")}+ </h3>+ {ingestion && parameters ? (+ <PolicyIngestionConfig+ parameters={parameters}+ target={target}+ allowExternal={false}+ engineReady={engineReady}+ indexingReady={indexingReady}+ chunkingReady={chunkingReady}+ checking={capabilities.isFetching}+ recheck={() => void capabilities.refetch()}+ onTargetChange={(next) =>+ patchIngestion(+ {+ index: next === "builtin",+ includeOriginal: true,+ exportChunksJsonl: next === "export",+ exportMarkdown: false,+ },+ next,+ )+ }+ onChange={(key, value) => {+ const next = { ...parameters, [key]: value };+ setDraft({ ...draft, [key]: value });+ patchIngestion({+ chunkSize: Number(next.chunkSize),+ overlap: Number(next.overlap),+ });+ }}+ >+ {outputDestination}+ </PolicyIngestionConfig>+ ) : (+ outputDestination+ )}+ </section>+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/FolderPolicySetupConfig.tsx b/frontend/editor/src/proprietary/components/policies/FolderPolicySetupConfig.tsxnew file mode 100644index 0000000000..c2fe9df6e4--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/FolderPolicySetupConfig.tsx@@ -0,0 +1 @@+export { PolicySetupConnections as FolderPolicySetupConfig } from "@portal/components/policies/PolicySetupConnections";diff --git a/frontend/editor/src/proprietary/components/policies/PolicyIngestionConfig.tsx b/frontend/editor/src/proprietary/components/policies/PolicyIngestionConfig.tsxnew file mode 100644index 0000000000..a7061500a7--- /dev/null+++ b/frontend/editor/src/proprietary/components/policies/PolicyIngestionConfig.tsx@@ -0,0 +1,164 @@+import { useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Banner, Button, Collapsible, FormField, Input, Select } from "@app/ui";+import type { PolicyParams } from "@app/policies/operations";+import { getSettingsUrl } from "@app/utils/settingsNavigation";++export type IngestionDestination = "builtin" | "external" | "export";++interface Props {+ parameters: PolicyParams<"ingest">;+ target: IngestionDestination;+ onTargetChange: (target: IngestionDestination) => void;+ onChange: (key: "chunkSize" | "overlap", value: string) => void;+ engineReady: boolean;+ indexingReady: boolean;+ chunkingReady: boolean;+ checking: boolean;+ recheck: () => void;+ allowExternal?: boolean;+ children?: ReactNode;+}++/** Guided ingestion choices, including setup recovery and chunk parameters. */+export function PolicyIngestionConfig({+ parameters,+ target,+ onTargetChange,+ onChange,+ engineReady,+ indexingReady,+ chunkingReady,+ checking,+ recheck,+ allowExternal = true,+ children,+}: Props) {+ const { t } = useTranslation();+ const [advanced, setAdvanced] = useState(false);+ return (+ <div className="portal-policies__capability-settings">+ <FormField+ label={t("portal.policies.wizard.locations.outputType", "Output type")}+ >+ <Select+ inputSize="sm"+ value={target}+ onChange={(value) =>+ value && onTargetChange(value as IngestionDestination)+ }+ options={[+ {+ value: "builtin",+ label: t(+ "portal.policies.wizard.locations.builtin",+ "Stirling knowledge base",+ ),+ },+ {+ value: "external",+ label: t(+ "portal.policies.wizard.locations.external",+ "Connected vector database",+ ),+ },+ {+ value: "export",+ label: t(+ "portal.policies.wizard.locations.export",+ "Export chunks without a database",+ ),+ },+ ].filter(+ (option) =>+ allowExternal ||+ option.value !== "external" ||+ target === "external",+ )}+ />+ </FormField>+ <p className="portal-policies__wizard-desc">+ {t(`portal.policies.wizard.locations.${target}Help`)}+ </p>+ {children}+ {checking ? (+ <p role="status">+ {t(+ "portal.policies.wizard.locations.checking",+ "Checking ingestion availability...",+ )}+ </p>+ ) : (+ (!engineReady || (parameters.index !== "false" && !indexingReady)) && (+ <Banner+ tone="warning"+ description={+ !engineReady+ ? t(+ "portal.policies.wizard.locations.engineUnavailable",+ "The AI engine is disabled or unreachable. Enable it to prepare chunks, or turn off knowledge search to run OCR only.",+ )+ : t(+ "portal.policies.wizard.locations.indexingUnavailable",+ "The built-in knowledge base needs an embedding provider. Configure one in AI settings, connect a vector database, or export chunks without a database.",+ )+ }+ />+ )+ )}+ <div className="portal-policies__setup-actions">+ <a+ className="portal-policies__setup-link"+ href={getSettingsUrl(+ target === "builtin" ? "adminAiDocuments" : "adminAiGeneral",+ )}+ target="_blank"+ rel="noreferrer"+ >+ {t("portal.policies.wizard.locations.aiSettings", "Open AI settings")}+ </a>+ <Button size="sm" variant="tertiary" onClick={() => recheck()}>+ {t("portal.policies.wizard.locations.recheck", "Check again")}+ </Button>+ </div>+ <Collapsible+ open={advanced}+ onToggle={() => setAdvanced(!advanced)}+ header={t(+ "portal.policies.wizard.locations.chunkSettings",+ "Chunk settings",+ )}+ >+ <div className="portal-policies__capability-settings">+ <FormField label={t("portal.pipelines.builder.ingest.chunkSize")}>+ <Input+ type="number"+ min={64}+ max={32768}+ value={parameters.chunkSize}+ onChange={(event) => onChange("chunkSize", event.target.value)}+ />+ </FormField>+ <FormField label={t("portal.pipelines.builder.ingest.overlap")}>+ <Input+ type="number"+ min={0}+ max={4096}+ value={parameters.overlap}+ onChange={(event) => onChange("overlap", event.target.value)}+ />+ </FormField>+ {!chunkingReady && (+ <Banner+ tone="warning"+ description={t(+ "portal.policies.wizard.locations.invalidChunks",+ "Choose a chunk size from 64 to 32768 and an overlap from 0 to 4096 smaller than the chunk size.",+ )}+ />+ )}+ </div>+ </Collapsible>+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.cssindex 6e72c8c4af..db2925dd71 100644--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css@@ -10,6 +10,7 @@.portal-policies__wizard-foot {display: flex;+ flex-wrap: wrap;align-items: center;gap: 0.5rem;width: 100%;@@ -78,3 +79,27 @@flex-direction: column;gap: 0.75rem;}++.portal-policies__setup-locations {+ border: 0;+ padding: 0;+ margin: 0;+ min-width: 0;+}+.portal-policies__setup-actions {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ flex-wrap: wrap;+}++/* Accent as text takes the deeper step: --c-accent-fg is --c-primary, which+ reads 3.67:1 on a light modal surface. */+.portal-policies__setup-link {+ color: var(--c-accent-text);+ font-size: 0.8125rem;+}++.portal-policies__wizard-foot > button {+ flex-shrink: 0;+}diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsxindex 070b80fb96..7ea4bf9a6c 100644--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx@@ -4,7 +4,15 @@ import {documentFieldCondition,requiresClassification,} from "@app/data/classificationConditions";-import { Fragment, useMemo, useState, type ReactNode } from "react";+import {+ Fragment,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from "react";import { useTranslation } from "react-i18next";import TuneRoundedIcon from "@mui/icons-material/TuneRounded";import { Banner, Button, Card, Modal, ToggleSwitch } from "@app/ui";@@ -46,6 +54,13 @@ export interface PolicySetupFrame {canSubmit: boolean;}+/** Additional settings share the wizard's draft and participate in its save validation. */+export interface PolicySetupConfigProps {+ result: PolicySetupResult;+ onChange: (patch: Partial<PolicySetupResult>) => void;+ onValidityChange: (valid: boolean) => void;+}+/** What the routing category binds: where documents come from, where each type goes. */export interface RoutingSetup {sourceId: string;@@ -66,6 +81,7 @@ interface PolicySetupWizardProps {onCustomise?: (entry: CatalogueEntry, result: PolicySetupResult) => void;/** Whether a Purview tenant is connected; gates the Purview-backed steps. */hasPurviewConnection?: boolean;+ setupConfig?: (props: PolicySetupConfigProps) => ReactNode;/*** Renders the routing category's source, routes and fallback destination. Folder hosts supply* their own input selection and render only the destinations here.@@ -183,7 +199,7 @@ const CAPABILITY_META: Record<labelEn: "Prepare for knowledge search",descKey: "portal.policies.wizard.capability.ingest.desc",descEn:- "Prepare searchable chunks for the built-in knowledge base, a connected RAG database, or a corpus export.",+ "Prepare searchable chunks for the built-in knowledge base, a connected vector database, or a corpus export.",},ocr: {labelKey: "portal.policies.wizard.capability.ocr.label",@@ -276,6 +292,9 @@ interface PolicySetupState {routing: RoutingSetup;tools: ToolState[];required: boolean;+ /** The host panel's half of the draft, and whether that panel accepts it. */+ settings: Partial<PolicySetupResult>;+ settingsValid: boolean;submitting: boolean;error: string | null;}@@ -283,8 +302,9 @@ interface PolicySetupState {function initialWizardState(entry: CatalogueEntry,aiClassificationEnabled: boolean,+ hasSetupConfig: boolean,): PolicySetupState {- const { category, policy } = entry;+ const { category, config, policy } = entry;const seeded = seedTools(entry);return {categoryId: category.id,@@ -309,6 +329,12 @@ function initialWizardState(? seeded.map((tool) => ({ ...tool, enabled: true })): seeded,required: policy?.state.required ?? category.id !== "classification",+ settings: {+ inputs: policy?.state.inputs ?? [],+ outputIds: policy?.state.outputIds ?? [],+ runsOnEditor: policy?.state.runsOnEditor ?? !config.needsSource,+ },+ settingsValid: !hasSetupConfig,submitting: false,error: null,};@@ -324,6 +350,7 @@ export function PolicySetupWizard({onSubmit,onCustomise,hasPurviewConnection,+ setupConfig,purviewConfig,routingConfig,formatError,@@ -339,6 +366,7 @@ export function PolicySetupWizard({onClose={onClose}onSubmit={onSubmit}onCustomise={onCustomise}+ setupConfig={setupConfig}hasPurviewConnection={hasPurviewConnection}purviewConfig={purviewConfig}routingConfig={routingConfig}@@ -359,6 +387,7 @@ function PolicySetupWizardBody({onSubmit,onCustomise,hasPurviewConnection = false,+ setupConfig,purviewConfig,routingConfig,formatError,@@ -373,6 +402,7 @@ function PolicySetupWizardBody({onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;onCustomise?: (entry: CatalogueEntry, result: PolicySetupResult) => void;hasPurviewConnection?: boolean;+ setupConfig?: (props: PolicySetupConfigProps) => ReactNode;purviewConfig?: (props: {parameters: PolicyParams<"purviewApplyLabel">;onChange: (params: PolicyParams<"purviewApplyLabel">) => void;@@ -396,15 +426,25 @@ function PolicySetupWizardBody({const isClassification = category.id === "classification";const isRouting = category.id === "routing";const [form, setForm] = useState(() =>- initialWizardState(entry, aiClassificationEnabled),+ initialWizardState(entry, aiClassificationEnabled, Boolean(setupConfig)),);- const { routing, tools, required, submitting, error } = form;+ const {+ routing,+ tools,+ required,+ settings,+ settingsValid,+ submitting,+ error,+ } = form;// Reset before rendering the new preset, preserving the modal and its focus trap.if (form.categoryId !== category.id ||form.policyId !== policy?.state.backendId) {- setForm(initialWizardState(entry, aiClassificationEnabled));+ setForm(+ initialWizardState(entry, aiClassificationEnabled, Boolean(setupConfig)),+ );}const fieldValues = resolveFieldValues(entry);const scopeTypes = policy?.state.scopeTypes ?? [];@@ -417,6 +457,24 @@ function PolicySetupWizardBody({const retryDelayMinutes = policy?.state.retryDelayMinutes ?? 0;const readOnly = !canManagePolicies;+ const errorRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!error) return;+ errorRef.current?.focus({ preventScroll: true });+ errorRef.current?.scrollIntoView?.({ block: "nearest" });+ }, [error]);+ // Stable identity: the host panel reports validity from an effect, which would+ // otherwise re-run every render.+ const setSettingsValid = useCallback(+ (valid: boolean) =>+ setForm((current) =>+ current.settingsValid === valid+ ? current+ : { ...current, settingsValid: valid },+ ),+ [],+ );+// Purview steps appear once a tenant is connected; an already-enabled one stays visible// so editing never silently drops it.const visibleTools = useMemo(@@ -460,21 +518,32 @@ function PolicySetupWizardBody({const routingNeedsClassification = routing.routingRules.some((rule) =>requiresClassification(rule.condition),);- const steps: PipelineStep[] = isRouting+ const selectedTools = isRouting? routingNeedsClassification- ? tools- .filter((tool) => tool.toolId === "classify")- .map((tool) => policyStepToWire(tool))+ ? tools.filter((tool) => tool.toolId === "classify"): []- : enabledTools.map((tool) => policyStepToWire(tool));+ : enabledTools;+ const steps: PipelineStep[] = selectedTools.map((tool) => {+ const step = policyStepToWire(tool);+ const saved = policy?.steps.find(+ (original) => original.operation === step.operation,+ );+ return {+ ...saved,+ ...step,+ parameters: { ...saved?.parameters, ...step.parameters },+ };+ });return {- required,+ required:+ (settings.runsOnEditor ?? true) &&+ !settings.outputIds?.length &&+ required,outputIds: policy?.state.outputIds,routingRules: policy?.state.routingRules,// Preserve stored options this wizard has no UI for rather than wiping them on save;// the builder is where those are edited.extraOptions: policy?.state.extraOptions,- runsOnEditor: !isRouting,fieldValues,sources: policy?.state.sources ?? [],scopeTypes,@@ -486,6 +555,7 @@ function PolicySetupWizardBody({maxRetries,retryDelayMinutes,steps,+ ...settings,...(isRouting? {sources: routing.sourceId ? [routing.sourceId] : [],@@ -494,6 +564,7 @@ function PolicySetupWizardBody({routingRules: routing.routingRules,}: {}),+ runsOnEditor: isRouting ? false : (settings.runsOnEditor ?? true),};}@@ -503,7 +574,7 @@ function PolicySetupWizardBody({}async function submit() {- if (submitting || !routingComplete) return;+ if (submitting || readOnly || !settingsValid || !routingComplete) return;if (!isRouting && enabledTools.length === 0) {setForm((current) => ({...current,@@ -540,15 +611,40 @@ function PolicySetupWizardBody({) &&(!routingNeedsClassification || aiClassificationEnabled),);- const canSubmit = isRouting ? routingComplete : enabledTools.length > 0;+ const canSubmit =+ (isRouting ? routingComplete : enabledTools.length > 0) &&+ settingsValid &&+ !readOnly;+ function updateSettings(patch: Partial<PolicySetupResult>) {+ const { steps, ...rest } = patch;+ const parsed = steps+ ?.map(policyStepFromWire)+ .filter((step) => step !== null);+ setForm((current) => ({+ ...current,+ settings: { ...current.settings, ...rest },+ tools: parsed+ ? current.tools.map((tool) => {+ const replacement = parsed.find(+ (step) => step.toolId === tool.toolId,+ );+ return replacement+ ? { ...replacement, enabled: true }+ : { ...tool, enabled: false };+ })+ : current.tools,+ }));+ }const content = (<Fragment key={`${category.id}:${policy?.state.backendId ?? "new"}`}>{error && !folderSetup && (- <Banner- tone="danger"- description={error}- className="portal-policies__wizard-banner"- />+ <div ref={errorRef} role="alert" tabIndex={-1}>+ <Banner+ tone="danger"+ description={error}+ className="portal-policies__wizard-banner"+ />+ </div>)}{isClassification && (@@ -613,6 +709,7 @@ function PolicySetupWizardBody({control={<ToggleSwitchsize="sm"+ disabled={readOnly}checked={tl.enabled}onChange={(checked) =>setToolEnabled(tl.toolId, checked)@@ -678,18 +775,26 @@ function PolicySetupWizardBody({</div>)}- {enforceControl && (- <div className="portal-policies__wizard-enforce">- <EnforceAsPolicyControl- required={required}- onRequiredChange={(next) =>- setForm((current) => ({ ...current, required: next }))- }- disabled={readOnly}- permissionsLoading={permissionsLoading}- />- </div>- )}+ {setupConfig?.({+ result: collectResult(),+ onChange: updateSettings,+ onValidityChange: setSettingsValid,+ })}++ {enforceControl &&+ settings.runsOnEditor !== false &&+ !settings.outputIds?.length && (+ <div className="portal-policies__wizard-enforce">+ <EnforceAsPolicyControl+ required={required}+ onRequiredChange={(next) =>+ setForm((current) => ({ ...current, required: next }))+ }+ disabled={readOnly}+ permissionsLoading={permissionsLoading}+ />+ </div>+ )}</Fragment>);if (children) {@@ -744,10 +849,10 @@ function PolicySetupWizardBody({</Button><Buttonsize="sm"- style={{ marginLeft: "auto" }}+ style={{ marginInlineStart: "auto" }}onClick={submit}loading={submitting}- disabled={readOnly || !routingComplete}+ disabled={!canSubmit}>{isEdit? t("portal.policies.wizard.actions.saveChanges")diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsxindex 93ad1282ff..f12926191f 100644--- a/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx@@ -165,7 +165,12 @@ export function ProcessingFolderSetupFlow({initialFolder={folder}aiEngineEnabled={aiEngineEnabled}catalogue={presets.catalogue}- destinations={routingDestinations(sources.data, outputModes)}+ // No vectordb: routing emits at most a classify step, never the chunks-only+ // ingest final step a vector database destination requires.+ destinations={routingDestinations(+ sources.data,+ outputModes.filter((mode) => mode !== "vectordb"),+ )}destinationsLoading={sources.loading}destinationsError={sources.error}onCreateDestination={() => {diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.test.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.test.tsxindex 1b2a9d0f47..3f750f19f6 100644--- a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.test.tsx+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.test.tsx@@ -26,8 +26,30 @@ const classification = vi.hoisted(() => ({ available: true }));vi.mock("@app/hooks/useAiClassificationEnabled", () => ({useAiClassificationEnabled: () => classification.available,}));+// The output panel is covered by its own tests; here it stands in for the wiring and the gate.+const setupConfigValid = vi.hoisted(() => ({ value: true }));+vi.mock("@app/components/policies/FolderPolicySetupConfig", async () => {+ const { useEffect } = await vi.importActual<typeof import("react")>("react");+ return {+ FolderPolicySetupConfig: ({+ folderName,+ onValidityChange,+ }: {+ folderName: string;+ onValidityChange: (valid: boolean) => void;+ }) => {+ useEffect(+ () => onValidityChange(setupConfigValid.value),+ [onValidityChange],+ );+ return <p>{`output panel for ${folderName}`}</p>;+ },+ };+});+beforeEach(() => {classification.available = true;+ setupConfigValid.value = true;});vi.mock("@app/services/directoryDrop", () => ({@@ -1103,7 +1125,7 @@ describe("ProcessingFolderWizard", () => {within(chooser).getByRole("button", {name: "portal.policies.categories.ingestion.label",}),- ).toBeDisabled();+ ).not.toBeDisabled();expect(within(chooser).getByRole("button", {name: "portal.policies.categories.retention.label",@@ -1226,4 +1248,22 @@ describe("ProcessingFolderWizard", () => {),);});++ it("mounts the output panel for every preset but Routing, and lets it block saving", () => {+ setupConfigValid.value = false;+ renderWizard({+ initialFolder: folder,+ destinations: [{ id: "archive", name: "Archive" }],+ });+ expect(screen.getByText(`output panel for ${folder.name}`)).toBeVisible();+ expect(button("enable")).toBeDisabled();+ fireEvent.click(+ screen.getByRole("button", {+ name: "portal.policies.categories.routing.label",+ }),+ );+ expect(+ screen.queryByText(`output panel for ${folder.name}`),+ ).not.toBeInTheDocument();+ });});diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsxindex 4f5a19e3f1..eea457ebda 100644--- a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx@@ -9,6 +9,7 @@ import {PolicyRoutingDestinations,type RoutingDestination,} from "@app/components/policies/PolicyRoutingDestinations";+import { FolderPolicySetupConfig } from "@app/components/policies/FolderPolicySetupConfig";import { PolicySetupWizard } from "@app/components/policies/PolicySetupWizard";import {ProcessingFolderPicker,@@ -174,6 +175,15 @@ export function ProcessingFolderWizard({onSubmit={submit}enforceControl={false}folderSetup+ // Routing picks its own destinations in routingConfig; every other preset configures its+ // output here, and its readiness check is what gates saving.+ setupConfig={+ entry.category.id === "routing"+ ? undefined+ : (config) => (+ <FolderPolicySetupConfig {...config} folderName={selectedName} />+ )+ }routingConfig={(props) => (<>{destinationsError && (diff --git a/frontend/editor/src/proprietary/components/policies/processingFolderSetup.test.ts b/frontend/editor/src/proprietary/components/policies/processingFolderSetup.test.tsindex 23f07b1f76..4958f27b8e 100644--- a/frontend/editor/src/proprietary/components/policies/processingFolderSetup.test.ts+++ b/frontend/editor/src/proprietary/components/policies/processingFolderSetup.test.ts@@ -82,10 +82,10 @@ describe("folder processing edits", () => {sortFolderPresets(configured).map((entry) => entry.category.id),).toEqual(["compliance",+ "ingestion","security","classification","routing",- "ingestion","retention",]);});diff --git a/frontend/editor/src/proprietary/policies/catalog.ts b/frontend/editor/src/proprietary/policies/catalog.tsindex 9b23654076..da647a1f31 100644--- a/frontend/editor/src/proprietary/policies/catalog.ts+++ b/frontend/editor/src/proprietary/policies/catalog.ts@@ -10,6 +10,7 @@ import {} from "@app/policies/operations";import type { ToolEndpoint } from "@app/types/toolApiTypes";import type {+ WirePipelineInput,WirePipelineStep,WireRoutingRule,WireTriggerConfig,@@ -44,12 +45,17 @@ export interface PolicyConfigDef {rules: string[];scopeLabel: string;fields: PolicyField[];+ /**+ * Whether the wizard asks where documents come from. Off by default: most templates run on+ * documents the user opens in the editor, so a source picker would be dead weight. On for+ * templates whose whole point is processing a location nobody is sitting in front of.+ */+ needsSource?: boolean;defaultOperations: PolicyToolStep[];}export interface PolicyState {/** The saved destinations and per-document routes; the routing category edits these. */- outputIds?: string[];routingRules?: WireRoutingRule[];trigger?: WireTriggerConfig | null;configured: boolean;@@ -61,6 +67,8 @@ export interface PolicyState {/** Options the wizard doesn't model, preserved so a wizard save round-trips them (see codec). */extraOptions?: Record<string, unknown>;sources: string[];+ inputs?: WirePipelineInput[];+ outputIds?: string[];/** Whether the editor runs this policy per file; stored, not derived from `sources`. */runsOnEditor?: boolean;scopeTypes: string[];@@ -79,13 +87,14 @@ export interface PolicyState {export interface PolicySetupResult {/** Bound by the routing category only; every other category leaves these alone. */trigger?: WireTriggerConfig | null;- outputIds?: string[];routingRules?: WireRoutingRule[];required: boolean;/** Stored options the wizard doesn't model, carried through so a save preserves them (see codec). */extraOptions?: Record<string, unknown>;fieldValues: Record<string, boolean | string | string[]>;sources: string[];+ inputs?: WirePipelineInput[];+ outputIds?: string[];runsOnEditor: boolean;scopeTypes: string[];reviewerEmail: string;@@ -156,9 +165,7 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [id: "ingestion",label: "portal.policies.categories.ingestion.label",tone: "blue",- desc: "portal.policies.categories.ingestion.desc",- providesClassification: true,- comingSoon: true,+ desc: "portal.policies.categories.ingestion.description",},{id: "security",@@ -196,7 +203,7 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {ingestion: {- summary: "portal.policies.config.ingestion.summary",+ summary: "portal.policies.config.ingestion.description",rules: ["portal.policies.config.ingestion.rules.0","portal.policies.config.ingestion.rules.1",@@ -204,23 +211,16 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {"portal.policies.config.ingestion.rules.3",],scopeLabel: "portal.policies.config.scopeAll",- defaultOperations: [policyStep("ocr"), policyStep("flatten")],- fields: [- {- label: "portal.policies.config.ingestion.fields.minConfidence",- key: "minConfidence",- type: "select",- value: "p80",- options: ["p60", "p70", "p80", "p90", "p95"],- },- {- label: "portal.policies.config.ingestion.fields.belowThreshold",- key: "belowThreshold",- type: "select",- value: "flagForReview",- options: ["flagForReview", "routeToBucket", "hold"],- },+ // OCR then ingest. Flatten is deliberately absent: a full flatten rasterises every+ // page, which destroys the text layer OCR just added and leaves ingest with+ // nothing to extract. OCR is seeded with a language because it validates on having+ // one, and a template that cannot be saved without opening a step is not a template.+ defaultOperations: [+ policyStep("ocr", { languages: ["eng"] }),+ policyStep("ingest"),],+ fields: [],+ needsSource: true,},security: {summary: "portal.policies.config.security.summary",diff --git a/frontend/editor/src/proprietary/policies/codec.ts b/frontend/editor/src/proprietary/policies/codec.tsindex 5ae9ea2082..acbfce601f 100644--- a/frontend/editor/src/proprietary/policies/codec.ts+++ b/frontend/editor/src/proprietary/policies/codec.ts@@ -78,6 +78,7 @@ export function toWirePolicy(state: PolicyDecodedState): WirePolicy {return {id: state.id,name: state.name,+ icon: state.icon,owner: "",enabled: state.enabled,required: state.required,@@ -119,6 +120,7 @@ export function fromWirePolicy(policy: WirePolicy): PolicyDecodedState {return {id: policy.id,name: policy.name,+ icon: policy.icon,enabled: policy.enabled,required: policy.required ?? false,policyKey,diff --git a/frontend/editor/src/proprietary/policies/overview.ts b/frontend/editor/src/proprietary/policies/overview.tsindex c1c37ea242..31bbe73fda 100644--- a/frontend/editor/src/proprietary/policies/overview.ts+++ b/frontend/editor/src/proprietary/policies/overview.ts@@ -28,6 +28,8 @@ function decoratePolicy(const status: PolicyStatus = decoded.enabled ? "active" : "paused";const state: PolicyState = {configured: true,+ name: decoded.name,+ icon: decoded.icon,outputIds: decoded.outputIds,routingRules: decoded.routingRules,status,@@ -35,6 +37,7 @@ function decoratePolicy(extraOptions: decoded.extraOptions,sources: decoded.sources,trigger: decoded.trigger,+ inputs: decoded.inputs,runsOnEditor: decoded.runsOnEditor,scopeTypes: decoded.scopeTypes,reviewerEmail: decoded.reviewerEmail,diff --git a/frontend/editor/src/prototypes/components/policies/FolderPolicySetupConfig.tsx b/frontend/editor/src/prototypes/components/policies/FolderPolicySetupConfig.tsxnew file mode 100644index 0000000000..5b99a698b1--- /dev/null+++ b/frontend/editor/src/prototypes/components/policies/FolderPolicySetupConfig.tsx@@ -0,0 +1 @@+export { FolderIngestionSettings as FolderPolicySetupConfig } from "@app/components/policies/FolderIngestionSettings";