Skip to content

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

64.6 KB
Raw Blame
import { EditorDeliverySelect } from "@processor/components/pipelines/EditorDeliverySelect";
import {
  parseTrigger,
  buildTriggerFor,
} from "@processor/components/pipelines/inputTriggerConfig";
import { requiresClassification } from "@editor/data/classificationConditions";
import { isConditionComplete } from "@editor/conditions/validation";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
import {
  ActionIcon,
  Banner,
  Button,
  FormField,
  Modal,
  Select,
  Spinner,
} from "@editor/ui";
import { useToolRegistry } from "@editor/contexts/ToolRegistryContext";
import {
  activeFileFields,
  assetRef,
  deserializeToolStep,
  extractStepFiles,
  getExecutableTools,
  newWorkingToolStep,
  serializeToolStep,
  stepNeedsConfiguring,
  updateWorkingStepParams,
  type ExecutableTool,
  type SupportingFileBindings,
  type WorkingToolStep,
} from "@editor/hooks/tools/shared/toolAutomation";
import {
  getToolFormatLabel,
  getToolFormatListLabel,
} from "@editor/utils/toolIOLabels";
import {
  chainOutputFormat,
  diagnosticsForStep,
  hasBlockingDiagnostics,
  validateToolChain,
  type ToolDiagnostic,
} from "@editor/utils/toolIOCompat";
import { errorMessage } from "@processor/api/http";
import {
  deletePipeline,
  fetchPipeline,
  fetchRun,
  fetchRunOutput,
  fetchTriggers,
  runPipelineTest,
  savePipeline,
  triggerPipeline,
  type PipelineStep,
  type Policy,
  type PolicyRunView,
  type RunOutputFile,
  type TestRunAsset,
  type TriggerInfo,
  type TriggerOutcome,
} from "@processor/api/pipelines";
import {
  listPipelineAssets,
  uploadPipelineAsset,
  type PolicyAsset,
} from "@processor/api/pipelineAssets";
import { clearProcessedHistory } from "@processor/api/policies";
import { DestinationPicker } from "@processor/components/pipelines/DestinationPicker";
import { RoutingSection } from "@processor/components/policies/RoutingRules";
import type { WireRoutingRule } from "@editor/policies/types";
import { availableOutputModes } from "@processor/components/pipelines/outputModes";
import { type SourceView } from "@processor/api/sources";
import { useSources } from "@processor/queries/sources";
import { useCanManagePolicies } from "@processor/queries/policyPermissions";
import { isReadableSource } from "@processor/components/sources/sourceTypes";
import { SourceModal } from "@processor/components/sources/SourceModal";
import { EDITOR_SOURCE_TYPE } from "@processor/components/sources/sourceTypes";
import { useAsync } from "@processor/hooks/useAsync";
import { useAiEngineEnabled } from "@processor/hooks/useAiEngineEnabled";
import { useQueryClient } from "@tanstack/react-query";
import { qk } from "@processor/queries/keys";
import { VIEW_PATHS, toPortalPath } from "@processor/contexts/ViewContext";
import { humanizeOperation } from "@processor/components/pipelines/pipelineOperations";
import { canonicalPipelineIconKey } from "@processor/components/pipelines/pipelineIcon";
import { PipelineCreateHeader } from "@processor/components/pipelines/PipelineCreateHeader";
import { PipelineEditHeader } from "@processor/components/pipelines/PipelineEditHeader";
import { PipelineGraphToolbar } from "@processor/components/pipelines/PipelineGraphToolbar";
import { PipelineInspector } from "@processor/components/pipelines/PipelineInspector";
import { PipelineDefinitionModal } from "@processor/components/pipelines/PipelineDefinitionModal";
import {
  PipelineGraph,
  selectedSteps,
  type ChainEnd,
  type ChainWarning,
  type GraphSelection,
  type GraphStepContent,
} from "@processor/components/pipelines/graph/PipelineGraph";
import {
  PipelineStepSettings,
  type ParamsUpdate,
} from "@processor/components/pipelines/PipelineStepSettings";
import { ToolPicker } from "@processor/components/pipelines/ToolPicker";
import { BrandMark } from "@processor/components/BrandMarks";
import { STEP_OPERATIONS } from "@processor/components/policies/stepOperations";
import {
  integrationStepConfigured,
  isIntegrationStep,
  newIntegrationStep,
  stepOperation,
} from "@processor/components/pipelines/integrationStep";
import {
  isIngestStep,
  ingestStepConfigured,
  needsCorpusDestination,
  vectorDestinationConfigured,
  prepareVectorDestination,
} from "@processor/components/pipelines/docparseStep";
import {
  MANUAL,
  MANUAL_OPTION,
  PipelineInputTrigger,
  type EditorRunOn,
  type WorkingInput,
} from "@processor/components/pipelines/PipelineInputTrigger";
import "@processor/views/PipelineBuilder.css";
import { PrivateContent } from "@editor/components/shared/PrivateContent";

const TERMINAL_STATUSES = new Set(["COMPLETED", "FAILED", "CANCELLED"]);
const POLL_INTERVAL_MS = 1500;
const POLL_ATTEMPTS = 60;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

type RunResult = {
  tone: "success" | "danger" | "info" | "warning";
  text: string;
};

/** The input row with nothing chosen yet: no source, manual trigger. */
function blankInput(): WorkingInput {
  return {
    sourceId: "",
    triggerType: MANUAL,
    scheduleCount: "1",
    scheduleUnit: "HOURS",
  };
}

/**
 * Routing reads the verdict this step writes, so a rule is only offered once the pipeline has one.
 * Mirrors ClassificationStepPlanner.CLASSIFY_ENDPOINT.
 */
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);
}

/**
 * Full-page pipeline builder (route: /pipelines/new and /pipelines/:id). Pipeline-level settings
 * (sources, trigger, output) sit above the operation list; the operation list and the selected
 * tool's settings sit side by side below. For an existing pipeline the header also runs and
 * deletes it. Replaces the former modal composer and the list's inline detail card.
 */
export function PipelineBuilder() {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  // Pipelines are stored as policies, so a save/delete must invalidate both the
  // pipelines overview and the policies caches (Policies page + Home) before
  // navigating back to the list.
  const invalidatePipelines = () =>
    Promise.all([
      queryClient.invalidateQueries({ queryKey: qk.pipelines() }),
      queryClient.invalidateQueries({ queryKey: qk.policiesList() }),
      queryClient.invalidateQueries({ queryKey: qk.policyRuns() }),
    ]);
  const { id } = useParams();
  const isEdit = Boolean(id);
  const location = useLocation();
  // A Customise hand-off from the simple policy wizard: the in-progress settings as a full pipeline
  // record, seeded here instead of fetched. When editing an existing policy the id-based fetch still
  // runs in the background so run/pause/delete act on the last-saved version.
  const handoff = location.state as { draft?: Policy } | null;
  const seedDraft = handoff?.draft ?? null;
  const {
    classificationEnabled: aiClassificationEnabled,
    loading: aiAvailabilityLoading,
  } = useAiEngineEnabled();
  const { allTools } = useToolRegistry();
  const executableTools = useMemo(
    () => getExecutableTools(allTools),
    [allTools],
  );

  // Stored supporting files from earlier saves, so a reopened step can label its bindings by name.
  const assetsState = useAsync<PolicyAsset[]>(
    async () => await listPipelineAssets(),
    [],
  );
  const assetNames = useMemo(() => {
    const map: Record<string, string> = {};
    for (const asset of assetsState.data ?? []) map[asset.id] = asset.fileName;
    return map;
  }, [assetsState.data]);

  const policyState = useAsync<Policy | null>(
    async () => (id ? await fetchPipeline(id) : null),
    [id],
  );
  const sourcesState = useSources();
  const { canManage: canManagePolicies, isLoading: permissionsLoading } =
    useCanManagePolicies();
  const triggersState = useAsync<TriggerInfo[]>(
    async () => await fetchTriggers(),
    [],
  );
  // Includes the virtual editor source: a valid input, but never a wire input (see save) and not
  // writable, so isWritableSource keeps it out of the destinations below.
  const availableSources = useMemo<SourceView[]>(
    () => sourcesState.data?.sources ?? [],
    [sourcesState.data],
  );
  // A destination is a source used as a write target: only writable types (folder/S3, filtered per
  // deployment) can be picked, and the virtual editor is already excluded from availableSources.
  const writableSources = useMemo<SourceView[]>(
    () => availableSources.filter(isWritableSource),
    [availableSources],
  );
  const triggers = useMemo(
    () => triggersState.data ?? [],
    [triggersState.data],
  );

  const [name, setName] = useState("");
  const [enabled, setEnabled] = useState(true);
  // Exactly one input: the row is always present, so the working state is a single object; the
  // wire shape stays a list (see save()).
  const [input, setInput] = useState<WorkingInput>(blankInput);
  // When the editor is the source, the pipeline fires client-side on each file: on upload as it
  // arrives, or on export as it leaves. Meaningless for a swept source, which has no such moment.
  const [runOn, setRunOn] = useState<EditorRunOn>("upload");
  const isEditorInput = useMemo(
    () =>
      availableSources.some(
        (source) =>
          source.id === input.sourceId && source.type === EDITOR_SOURCE_TYPE,
      ),
    [availableSources, input.sourceId],
  );
  const [steps, setSteps] = useState<WorkingToolStep[]>([]);
  /** Which node the inspector is editing: an end of the chain, a step, or nothing. */
  const [selected, setSelected] = useState<GraphSelection>(null);
  /** Slot the tool picker will insert into, or null when it is closed. */
  const [pickerAt, setPickerAt] = useState<number | null>(null);
  const [definitionOpen, setDefinitionOpen] = useState(false);
  /** The last test run in this session: one file through the steps as they stand. */
  const [testRun, setTestRun] = useState<PolicyRunView | null>(null);
  const [testing, setTesting] = useState(false);
  const [outputIds, setOutputIds] = useState<string[]>([]);
  const [routingRules, setRoutingRules] = useState<WireRoutingRule[]>([]);
  // A policy (blocking on failure) vs an ordinary pipeline (see Policy.required). Only meaningful for
  // an editor-sourced pipeline, so the toggle is shown only then and reset off otherwise (see save).
  const [required, setRequired] = useState(false);
  // First-class row icon (see Policy.icon), chosen from the picker in the header. Empty falls back to
  // the template category glyph in the list; a custom pipeline defaults to none until picked.
  const [icon, setIcon] = useState("");
  // The policy metadata bag carried on output.options (runOn, sources, output naming, scope,
  // reviewer, fieldValues...). Seeded on load and written back untouched, so a customised policy
  // never loses its simple-only settings even though the builder has no UI for them.
  const [outputOptions, setOutputOptions] = useState<Record<string, unknown>>(
    {},
  );
  const [destinationRequested, setDestinationRequested] = useState(false);
  const requiresDestination = needsCorpusDestination(steps);
  const externalEditorOutput =
    isEditorInput &&
    (requiresDestination || outputIds.length > 0 || destinationRequested);
  const returnsToEditor = isEditorInput && !externalEditorOutput;
  const [outputType, setOutputType] = useState("inline");
  /**
   * Whether the user has asked for each end of the chain yet, distinguishing "not offered" from
   * "offered and still owed a choice" - the two states an empty sourceId cannot tell apart. Only a
   * brand new pipeline starts with either false; anything loaded arrives with both ends set, and
   * choosing one places it, so these are just the "clicked add, chosen nothing" window.
   */
  const [inputAsked, setInputAsked] = useState(false);
  const [outputAsked, setOutputAsked] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  // Which create action is in flight, so only the button that was clicked (Create / Create paused)
  // shows its spinner. Null in edit and while idle.
  const [pendingCreateEnabled, setPendingCreateEnabled] = useState<
    boolean | null
  >(null);
  const [error, setError] = useState<string | null>(null);
  const [seeded, setSeeded] = useState(false);
  const [running, setRunning] = useState(false);
  // Pausing/activating an existing pipeline acts immediately (a separate save), not on the next
  // "Save changes"; this tracks that in-flight toggle.
  const [togglingEnabled, setTogglingEnabled] = useState(false);
  // Clearing the processed record then running, so already-handled files go through again.
  const [reprocessing, setReprocessing] = useState(false);
  const [runResult, setRunResult] = useState<RunResult | null>(null);
  const [pendingDelete, setPendingDelete] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [pendingNav, setPendingNav] = useState<string | null>(null);

  // Create or edit a source in place, instead of leaving the builder (and its
  // unsaved edits) for the Sources page.
  const [sourceModal, setSourceModal] = useState<{
    open: boolean;
    sourceId: string | null;
    direction?: "input" | "output";
  }>({ open: false, sourceId: null });
  function createSourceFor(target: "input" | "output") {
    setSourceModal({ open: true, sourceId: null, direction: target });
  }

  const mounted = useRef(true);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);

  // Seed the form once: immediately for a new pipeline or a Customise hand-off, or after the policy
  // loads for an edit. A hand-off draft wins over the fetched record (it carries the unsaved wizard
  // edits), so an edit reached via Customise need not wait for the fetch.
  useEffect(() => {
    if (seeded) return;
    if (isEdit && !seedDraft && !policyState.data) return;
    const policy = seedDraft ?? policyState.data ?? undefined;
    // An editor pipeline is recognised by the editor source id, which arrives with the sources
    // fetch. If the policy loads first, seeding now would latch a blank input and re-save the
    // pipeline off the editor (editor.allowed:false), so wait for that fetch to settle.
    if (policy?.editor?.allowed && !sourcesState.data && !sourcesState.error) {
      return;
    }
    setName(policy?.name ?? "");
    setEnabled(policy?.enabled ?? true);
    setRequired(policy?.required ?? false);
    // Seed the icon from the first-class field; a template hand-off has none yet, so fall back to its
    // category id. Normalise either to a canonical pickable key - the picker matches its own
    // vocabulary, not the category-id aliases, so an unnormalised categoryId shows as the default.
    const seedCategoryId = policy?.output?.options?.categoryId;
    setIcon(
      canonicalPipelineIconKey(
        policy?.icon ??
          (typeof seedCategoryId === "string" ? seedCategoryId : ""),
      ),
    );
    setOutputOptions(policy?.output?.options ?? {});
    setOutputType(policy?.output?.type ?? "inline");
    // The one input row is always present: blank for a new pipeline (or a legacy policy saved
    // without inputs), the stored input for an edit. A legacy multi-input policy shows only its
    // first input; saving persists just that one (the backend rejects more anyway).
    // An editor pipeline has no wire input; it is recognised by its recorded sources.
    const editorSourceId = (sourcesState.data?.sources ?? []).find(
      (source) => source.type === EDITOR_SOURCE_TYPE,
    )?.id;
    setRunOn(policy?.editor?.runOn === "export" ? "export" : "upload");
    const stored = policy?.inputs[0];
    const seedsEditor = Boolean(policy?.editor?.allowed && editorSourceId);
    if (seedsEditor && editorSourceId) {
      setInput({ ...blankInput(), sourceId: editorSourceId });
    } else if (stored) {
      const trigger = parseTrigger(stored.trigger);
      setInput({
        sourceId: stored.sourceId,
        triggerType: trigger.triggerType,
        scheduleCount: trigger.count,
        scheduleUnit: trigger.unit,
      });
    } else {
      setInput(blankInput());
    }
    setSteps(
      (policy?.steps ?? []).map((step) => deserializeToolStep(step, allTools)),
    );
    setOutputIds(policy?.outputIds ?? []);
    setRoutingRules(policy?.routingRules ?? []);
    setDestinationRequested(
      seedsEditor &&
        ((policy?.outputIds?.length ?? 0) > 0 ||
          (policy?.routingRules?.length ?? 0) > 0),
    );
    setSeeded(true);
  }, [
    isEdit,
    seedDraft,
    policyState.data,
    allTools,
    seeded,
    sourcesState.data,
    sourcesState.error,
  ]);

  const sourceType = (sourceId: string) =>
    availableSources.find((s) => s.id === sourceId)?.type;

  // A trigger fits a source when it needs no source, or the source's type is one it supports
  // (folder-watch → folder; schedule → any). Drives the per-input trigger dropdown.
  const triggerFitsType = (trigger: TriggerInfo, type: string) =>
    !trigger.requiresSource || trigger.supportedSourceTypes.includes(type);

  const sourceOptions = availableSources
    .filter(isReadableSource)
    .map((source) => ({
      value: source.id,
      label: source.name,
    }));

  // Manual plus every trigger compatible with this row's source. Manual only until a source is set.
  function triggerOptionsFor(sourceId: string) {
    const options = [
      {
        value: MANUAL_OPTION,
        label: t("portal.pipelines.composer.triggerManual"),
      },
    ];
    const type = sourceType(sourceId);
    if (type) {
      for (const trigger of triggers) {
        if (triggerFitsType(trigger, type)) {
          options.push({
            value: trigger.type,
            label: t(`portal.pipelines.trigger.${trigger.type}`, {
              defaultValue: trigger.type,
            }),
          });
        }
      }
    }
    return options;
  }

  function updateInput(patch: Partial<WorkingInput>) {
    setInput((current) => ({ ...current, ...patch }));
  }

  // Changing the source may make the current trigger incompatible (folder-watch on a non-folder);
  // drop it back to manual when that happens so the row can't hold an invalid pairing.
  function changeInputSource(sourceId: string) {
    const type = sourceType(sourceId);
    setInput((current) => {
      const trigger = triggers.find((tr) => tr.type === current.triggerType);
      const keepTrigger =
        current.triggerType === MANUAL ||
        (type != null && trigger != null && triggerFitsType(trigger, type));
      return {
        ...current,
        sourceId,
        triggerType: keepTrigger ? current.triggerType : MANUAL,
      };
    });
  }

  /** Put an end on the chain and open it, so the click that asks for it also offers the choice. */
  function addEnd(end: ChainEnd) {
    if (end === "input") setInputAsked(true);
    else setOutputAsked(true);
    setSelected(end);
  }

  /** Take an end back off, discarding whatever it held so its row reads as unfilled again. */
  function removeEnd(end: ChainEnd) {
    if (end === "input") {
      setInputAsked(false);
      setInput(blankInput());
    } else {
      setOutputAsked(false);
      setOutputIds([]);
    }
    setSelected((current) => (current === end ? null : current));
  }

  /** Drop a new step into the slot the picker was opened on, and select it to be configured. */
  function insertStep(step: WorkingToolStep) {
    const at = pickerAt ?? steps.length;
    setSteps((current) => {
      const next = [...current];
      next.splice(at, 0, step);
      return next;
    });
    setSelected({ steps: [at] });
    setPickerAt(null);
  }

  function addOperationStep(op: (typeof STEP_OPERATIONS)[number]) {
    insertStep(newIntegrationStep(op));
  }

  function addStep(tool: ExecutableTool) {
    insertStep(newWorkingToolStep(tool, allTools));
  }

  function removeSteps(indices: number[]) {
    const gone = new Set(indices);
    setSelected(null);
    setSteps((current) => current.filter((_, i) => !gone.has(i)));
  }

  /**
   * Apply a reordered chain, given as the original step indices in their new positions. The steps
   * the drag carried stay selected where they land, so a set can be dragged again without re-picking
   * it - and dragging an unselected step selects it, rather than leaving the inspector on whatever
   * was selected before.
   */
  function reorderSteps(order: number[], moved: readonly number[]) {
    const moving = new Set(moved);
    setSteps((current) => order.map((i) => current[i]));
    const landed = order
      .map((original, position) => ({ original, position }))
      .filter(({ original }) => moving.has(original))
      .map(({ position }) => position);
    setSelected(landed.length > 0 ? { steps: landed } : null);
  }

  function updateStepParams(index: number, update: ParamsUpdate) {
    setSteps((current) =>
      current.map((step, i) => {
        // Integration and DocParse steps are deliberately toolId-less, so they must be editable
        // too; only a genuinely unrecognised step has no editor to send changes from.
        if (
          i !== index ||
          (step.toolId === null &&
            !isIntegrationStep(step) &&
            !isIngestStep(step))
        )
          return step;
        // Resolve the update against the CURRENT step params, so a settings UI firing several
        // single-field changes in one tick (convert's source-format change resets target + options)
        // accumulates instead of each merge clobbering a stale snapshot. updateWorkingStepParams
        // also re-resolves the endpoint for a format-routed tool so validation reflects the edit;
        // it's a no-op on the operation for fixed-endpoint steps.
        const nextParams =
          typeof update === "function" ? update(step.params) : update;
        return updateWorkingStepParams(step, nextParams, allTools);
      }),
    );
  }

  /** Drop a step's stored supporting-file binding for one field (the chip's remove action). */
  function clearStepBinding(index: number, field: string) {
    setSteps((current) =>
      current.map((step, i) => {
        if (i !== index || !step.fileParameters) return step;
        const next = { ...step.fileParameters };
        delete next[field];
        return {
          ...step,
          fileParameters: Object.keys(next).length > 0 ? next : undefined,
        };
      }),
    );
  }

  function stepLabel(step: WorkingToolStep): string {
    // An integration step's endpoint is the same for every vendor, so the raw path would read
    // "External api call" for all of them. Name it by the operation instead.
    const op = stepOperation(step);
    if (op) return t(op.labelKey);
    if (isIntegrationStep(step))
      return t("portal.pipelines.builder.sendToSystem");
    if (isIngestStep(step)) return t("portal.policies.endpoints.ingest");
    const entry = step.toolId ? allTools[step.toolId] : undefined;
    return entry?.name ?? humanizeOperation(step.operation);
  }

  /**
   * A step's glyph, matching how the tool picker draws it: an integration step carries its vendor's
   * mark, a tool step its own icon. Without this every node falls back to the generic slider glyph,
   * so a chain reads as a stack of identical cards.
   */
  function stepIcon(step: WorkingToolStep): ReactNode {
    const op = stepOperation(step);
    if (op)
      return (
        <BrandMark id={op.custom ? "api" : op.connectionTypeId} size={18} />
      );
    if (isIntegrationStep(step)) return <BrandMark id="api" size={18} />;
    return step.toolId ? allTools[step.toolId]?.icon : undefined;
  }

  // A step still missing a choice - an integration with no operation or account, a tool whose
  // mandatory parameters are unset - would fail at run time with a raw backend rejection, so block
  // saving on it here where the fix is one click away.
  const unconfiguredStepLabels = steps
    .filter(
      (step) =>
        !integrationStepConfigured(step) ||
        !ingestStepConfigured(step, returnsToEditor) ||
        stepNeedsConfiguring(step, allTools),
    )
    .map(stepLabel);
  const hasUnconfiguredSteps = unconfiguredStepLabels.length > 0;

  // Steps as the I/O checker sees them. A step still needing configuration has no settled endpoint
  // yet (a format-routed tool like convert doesn't know its from/to), so it is presented as
  // undeclared: it raises no compatibility error and breaks the carry chain, leaving downstream
  // steps unjudged until it is filled in. Its own "needs configuring" note already flags it.
  const validationSteps = useMemo(
    () =>
      steps.map((step) => ({
        operation: stepNeedsConfiguring(step, allTools) ? "" : step.operation,
        parameters: step.params,
      })),
    [steps, allTools],
  );

  // Whether each step can actually accept what the one before it produces. Checked here from the
  // generated tool I/O table rather than by running the pipeline, so an impossible chain (say,
  // Extract Images then Rotate) is caught while it is being built.
  const chainDiagnostics = useMemo(
    () =>
      validateToolChain(validationSteps).filter(
        (d) => !stepNeedsConfiguring(steps[d.stepIndex], allTools),
      ),
    [validationSteps, steps, allTools],
  );
  const blockingSteps = chainDiagnostics
    .filter((d) => d.severity === "ERROR")
    .map((d) => stepLabel(steps[d.stepIndex]));
  const hasIncompatibleSteps = hasBlockingDiagnostics(chainDiagnostics);

  /**
   * What a step added at the open slot would be handed, so the picker can flag tools that cannot
   * take it. Scoped to the steps *before* that slot rather than the whole chain: the graph inserts
   * anywhere, so what precedes the new step is not necessarily the chain's final output. Sliced from
   * the validation view so an unconfigured step before the slot yields an unknown (undefined) format
   * rather than a misleading one from its placeholder endpoint.
   */
  const precedingOutput = useMemo(
    () =>
      pickerAt === null
        ? undefined
        : chainOutputFormat(validationSteps.slice(0, pickerAt)),
    [validationSteps, pickerAt],
  );

  function diagnosticNote(diagnostic: ToolDiagnostic): string {
    const { accepts, produced } = diagnostic.detail;
    return t(`portal.pipelines.builder.diagnostic.${diagnostic.code}`, {
      accepts: getToolFormatListLabel(t, i18n.language, accepts ?? []),
      produced: produced ? getToolFormatLabel(t, produced) : "",
    });
  }

  /**
   * The step's most severe diagnostic, for the wire arriving at it - which is where a note about
   * what the step is being handed belongs, rather than on the step itself.
   */
  function stepInputWarning(index: number): ChainWarning | undefined {
    const forStep = diagnosticsForStep(chainDiagnostics, index);
    const diagnostic =
      forStep.find((d) => d.severity === "ERROR") ??
      forStep.find((d) => d.severity === "WARN") ??
      forStep[0];
    if (!diagnostic) return undefined;
    return {
      text: diagnosticNote(diagnostic),
      blocking: diagnostic.severity === "ERROR",
    };
  }

  // Track unsaved edits: snapshot the form and compare against the state captured just after
  // seeding, so leaving the builder can prompt to save or discard. `enabled` is deliberately left
  // out: in edit it is toggled and persisted at once (never an unsaved edit), and in create it is
  // chosen at submit - so it can never be the thing that makes the form dirty.
  // Per-step dirty signature: the serialized step plus a stable identity (name/size/mtime) of its
  // fresh file picks - a raw File JSON-stringifies to `{}`, so serializeToolStep (which excludes
  // Files) can't see a file added or swapped. Memoized on the steps because it probes each tool's
  // buildFormData; without this it would re-run for every step on any render (e.g. each keystroke in
  // the name field). Stored bindings are covered by the serialized step.
  const stepSnapshot = useMemo(
    () =>
      steps.map((step) => {
        const files: Record<string, string[]> = {};
        for (const [field, picks] of Object.entries(
          extractStepFiles(step, allTools),
        )) {
          files[field] = picks.map(
            (file) => `${file.name}:${file.size}:${file.lastModified}`,
          );
        }
        return { step: serializeToolStep(step, allTools), files };
      }),
    [steps, allTools],
  );
  const snapshot = JSON.stringify({
    name: name.trim(),
    icon,
    required,
    input,
    steps: stepSnapshot,
    outputType,
    outputOptions,
    outputIds: [...outputIds].sort(),
    routingRules,
  });
  const baseline = useRef<string | null>(null);
  useEffect(() => {
    if (seeded && baseline.current === null) baseline.current = snapshot;
  }, [seeded, snapshot]);
  const dirty = baseline.current !== null && baseline.current !== snapshot;

  const stepsSignature = JSON.stringify(stepSnapshot);
  const testedStepsSignature = useRef<string | null>(null);
  useEffect(() => {
    if (
      testedStepsSignature.current !== null &&
      testedStepsSignature.current !== stepsSignature
    ) {
      testedStepsSignature.current = null;
      setTestRun(null);
    }
  }, [stepsSignature]);

  // Each validity condition is defined exactly once here, then consumed both by the graph (which
  // flags each end) and by the blocker list below.
  const sourceChosen = availableSources.some(
    (source) => source.id === input.sourceId && isReadableSource(source),
  );
  // An editor pipeline has no trigger to schedule: it fires as each file passes through.
  const scheduleValid =
    isEditorInput ||
    input.triggerType !== "schedule" ||
    Number(input.scheduleCount) > 0;
  const inputValid = sourceChosen && scheduleValid;
  const destinationIds = new Set([
    ...outputIds,
    ...routingRules.map((rule) => rule.outputId),
  ]);
  const vectorOutput = writableSources.some(
    (source) => destinationIds.has(source.id) && source.type === "vectordb",
  );
  const vectorReady = !vectorOutput || vectorDestinationConfigured(steps);
  const destinationReady =
    outputIds.length === 1 &&
    writableSources.some(
      (source) => source.id === outputIds[0] && source.status !== "disabled",
    );
  const outputValid = returnsToEditor || (destinationReady && vectorReady);
  const classifies = steps.some(isClassifyStep);
  // Mirrors PolicyValidator.validateRoutingRules: a rule with nothing to match on, or nowhere to
  // send, would be rejected on save - so it is named here rather than surfaced as a server error.
  const routingValid = routingRules.every(
    (rule) => isConditionComplete(rule.condition) && rule.outputId !== "",
  );
  // Rules outliving the step that feeds them: the classify step was removed after they were set.
  // Every document would fall through to the fallback, so this is named rather than left to run.
  const routingHasVerdict = routingRules.every(
    (rule) => !requiresClassification(rule.condition) || classifies,
  );

  // The single source of truth for "can this be committed": every reason it can't be, in the order
  // they appear down the form, so a disabled Create / Save button can say exactly what is still owed.
  const blockers: string[] = [];
  if (name.trim() === "")
    blockers.push(t("portal.pipelines.builder.blocker.name"));
  if (!sourceChosen)
    blockers.push(t("portal.pipelines.builder.blocker.source"));
  else if (!scheduleValid)
    blockers.push(t("portal.pipelines.builder.blocker.schedule"));
  if (!returnsToEditor && !destinationReady)
    blockers.push(t("portal.pipelines.builder.blocker.destination"));
  if (!vectorReady)
    blockers.push(t("portal.pipelines.builder.ingest.destinationNeedsChunks"));
  if (!routingValid)
    blockers.push(
      t(
        "portal.pipelines.builder.blocker.routing",
        "Give every route document types and a destination",
      ),
    );
  if (!routingHasVerdict)
    blockers.push(
      t(
        "portal.pipelines.builder.blocker.routingNeedsClassify",
        "Add a Classify step, or turn off routing by document type",
      ),
    );
  if (classifies && !aiAvailabilityLoading && !aiClassificationEnabled)
    blockers.push(
      t(
        "portal.pipelines.builder.blocker.aiClassification",
        "Enable AI classification in Settings, or remove the Classify step",
      ),
    );
  if (hasUnconfiguredSteps)
    blockers.push(
      t("portal.pipelines.builder.blocker.setup", {
        tools: unconfiguredStepLabels.join(", "),
      }),
    );
  if (hasIncompatibleSteps)
    blockers.push(
      t("portal.pipelines.builder.blocker.incompatible", {
        tools: blockingSteps.join(", "),
      }),
    );

  // Nothing left to fix, and not already committing.
  const canSave = blockers.length === 0 && !submitting;

  const listPath = toPortalPath(VIEW_PATHS.pipelines);

  function close() {
    navigate(listPath);
  }

  // Leave the builder, but prompt first if there are unsaved edits (see the unsaved-changes modal).
  function attemptLeave(destination: string) {
    if (dirty) setPendingNav(destination);
    else navigate(destination);
  }

  /**
   * The active supporting-file fields of a step, each paired with its fresh in-memory pick(s) and its
   * stored `asset:<id>` binding (either may be absent). The single source both saving and test-running
   * read, so the two agree on which fields are active and how a binding is chosen; they differ only in
   * how a fresh pick is emitted - uploaded as an asset vs. sent inline.
   */
  function stepFileFields(
    step: WorkingToolStep,
  ): { field: string; fresh: File[] | null; stored: string | null }[] {
    const fresh = extractStepFiles(step, allTools);
    const stored = step.fileParameters ?? {};
    const fields = activeFileFields(step, allTools) ?? Object.keys(stored);
    return fields.map((field) => ({
      field,
      fresh: fresh[field] ?? null,
      stored: stored[field] ?? null,
    }));
  }

  /** A wire step, attaching fileParameters only when it has any. */
  function toWireStep(
    operation: string,
    parameters: Record<string, unknown>,
    bindings: SupportingFileBindings,
  ): PipelineStep {
    return Object.keys(bindings).length > 0
      ? { operation, parameters, fileParameters: bindings }
      : { operation, parameters };
  }

  /**
   * The wire steps for saving: scalar params from serialization, plus supporting-file bindings. A
   * fresh pick is uploaded to the asset store (the save-time validator rejects a policy that binds an
   * asset id that doesn't yet exist); a stored binding the tool still uses is kept when the user
   * didn't replace it. Uploads run in parallel; any abandoned by a later failure are GC'd server-side.
   */
  async function serializeStepsForSave(): Promise<PipelineStep[]> {
    return Promise.all(
      steps.map(async (step) => {
        const { operation, parameters } = serializeToolStep(step, allTools);
        const entries = await Promise.all(
          stepFileFields(step).map(async ({ field, fresh, stored }) => {
            if (fresh?.length) {
              const ids = await Promise.all(
                fresh.map((file) =>
                  uploadPipelineAsset(file).then((a) => a.id),
                ),
              );
              return [field, assetRef(ids)] as const;
            }
            return stored ? ([field, stored] as const) : null;
          }),
        );
        const bindings: SupportingFileBindings = Object.fromEntries(
          entries.filter((e): e is readonly [string, string] => e !== null),
        );
        return toWireStep(operation, parameters, bindings);
      }),
    );
  }

  async function save(destination: string, enabledOverride?: boolean) {
    if (!canSave) return;
    setSubmitting(true);
    setError(null);
    try {
      const policy: Policy = {
        id: policyState.data?.id ?? seedDraft?.id ?? undefined,
        name: name.trim(),
        enabled: enabledOverride ?? enabled,
        // Blocking is only meaningful for an editor pipeline; a source-backed one is never a policy,
        // so don't persist a stale flag if the source was switched away from the editor.
        required: returnsToEditor && required,
        icon,
        // The editor is virtual - there is no stored Source to pull from, and nothing server-side
        // sweeps it - so it is never a wire input; its participation is recorded on `editor` below.
        inputs: isEditorInput
          ? []
          : [{ sourceId: input.sourceId, trigger: buildTriggerFor(input) }],
        steps: await serializeStepsForSave(),
        // The output carries the policy metadata bag (categoryId, scope, naming...), edited in the
        // dev section and preserved verbatim otherwise, so a customised policy never loses it.
        output: { type: outputType, options: outputOptions },
        editor: { allowed: isEditorInput, runOn },
        // An editor pipeline delivers back into the workspace. A stored destination would send the
        // run to a folder or bucket instead, leaving the editor's copy untouched.
        outputIds: returnsToEditor ? [] : outputIds,
        routingRules: returnsToEditor ? [] : routingRules,
      };
      await savePipeline(policy);
      await invalidatePipelines();
      navigate(destination);
    } catch (e) {
      setError(errorMessage(e));
      setSubmitting(false);
      setPendingCreateEnabled(null);
    }
  }

  // Create live or paused. The buttons disable until the pipeline is valid, so this only fires on a
  // saveable pipeline; the flag records which button spins and whether it starts live or paused.
  function submitCreate(enabledValue: boolean) {
    setPendingCreateEnabled(enabledValue);
    void save(listPath, enabledValue);
  }

  /**
   * Pause or activate the saved pipeline now, without leaving the builder. It re-saves the
   * persisted policy with the flag flipped - deliberately NOT the working form - so a pending chain
   * edit is not silently committed by a pause. The dirty tracker ignores `enabled`, so this never
   * looks like an unsaved change.
   */
  async function handleTogglePause() {
    // Never run alongside a Save: both write the whole policy, and a concurrent pair would race
    // (the pause carries the persisted steps, so it could clobber the edits Save is committing).
    if (togglingEnabled || submitting || !policyState.data) return;
    const next = !enabled;
    setTogglingEnabled(true);
    setError(null);
    try {
      await savePipeline({ ...policyState.data, enabled: next });
      if (!mounted.current) return;
      setEnabled(next);
      await invalidatePipelines();
    } catch (e) {
      if (mounted.current) setError(errorMessage(e));
    } finally {
      if (mounted.current) setTogglingEnabled(false);
    }
  }

  // Poll a run until it reaches a terminal state (or we give up), so a failure surfaces.
  async function awaitRun(
    runId: string,
    onProgress?: (view: PolicyRunView) => void,
  ): Promise<PolicyRunView | null> {
    for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt++) {
      if (!mounted.current) return null;
      const view = await fetchRun(runId);
      onProgress?.(view);
      if (TERMINAL_STATUSES.has(view.status)) return view;
      await sleep(POLL_INTERVAL_MS);
    }
    return null;
  }

  /**
   * The steps + inline supporting files for a test run. A fresh (in-memory) pick rides along as a
   * keyed `assets[i]` under a per-step run key; a stored file keeps its `asset:<id>` binding, which
   * the backend resolves from the pipeline's saved policy (passed as policyId) - no re-fetch needed.
   */
  function buildTestSteps(): { steps: PipelineStep[]; assets: TestRunAsset[] } {
    const assets: TestRunAsset[] = [];
    const outSteps = steps.map((step, i) => {
      const { operation, parameters } = serializeToolStep(step, allTools);
      const bindings: SupportingFileBindings = {};
      for (const { field, fresh, stored } of stepFileFields(step)) {
        if (fresh?.length) {
          // In-memory pick: inline the bytes under a run key.
          const key = `s${i}_${field}`;
          bindings[field] = key;
          for (const file of fresh) assets.push({ key, file });
        } else if (stored) {
          // Already an asset: keep its ref for the backend to resolve from the saved policy.
          bindings[field] = stored;
        }
      }
      return toWireStep(operation, parameters, bindings);
    });
    return { steps: outSteps, assets };
  }

  /**
   * Run the steps as they stand against one uploaded file. Output is forced inline so nothing
   * reaches the pipeline's real destination, and the pipeline need not be saved first - this is
   * how the chain gets checked while it is still being built.
   */
  async function handleTest(file: File) {
    if (testing) return;
    setTesting(true);
    setTestRun(null);
    testedStepsSignature.current = stepsSignature;
    setRunResult(null);
    try {
      const { steps: testSteps, assets } = buildTestSteps();
      const { runId } = await runPipelineTest(
        {
          name: name.trim() || t("portal.pipelines.builder.testRun"),
          steps: testSteps,
          output: { type: "inline", options: {} },
        },
        file,
        assets,
        // Lets the backend resolve any stored `asset:<id>` refs from this saved policy.
        policyState.data?.id,
      );
      const final = await awaitRun(runId, (view) => {
        if (mounted.current) setTestRun(view);
      });
      if (mounted.current && final) setTestRun(final);
    } catch (e) {
      if (mounted.current)
        setRunResult({ tone: "danger", text: errorMessage(e) });
    } finally {
      if (mounted.current) setTesting(false);
    }
  }

  /** Save one of a test run's outputs to disk. */
  async function downloadOutput(output: RunOutputFile) {
    try {
      const blob = await fetchRunOutput(output.fileId);
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = output.fileName ?? output.fileId;
      link.click();
      // Revoke on the next tick: some browsers have not yet begun reading the
      // blob when click() returns, and revoking now would cancel the download.
      setTimeout(() => URL.revokeObjectURL(url), 0);
    } catch (e) {
      if (mounted.current)
        setRunResult({ tone: "danger", text: errorMessage(e) });
    }
  }

  /** Explain an empty trigger: parked files outrank blander reasons. */
  function emptySweepResult(outcome: TriggerOutcome): RunResult {
    if (outcome.parked > 0) {
      return {
        tone: "warning",
        text: t("portal.pipelines.run.parked", { count: outcome.parked }),
      };
    }
    if (outcome.inFlight > 0) {
      return { tone: "info", text: t("portal.pipelines.run.inFlight") };
    }
    if (outcome.alreadyProcessed > 0) {
      return {
        tone: "info",
        text: t("portal.pipelines.run.allProcessed", {
          count: outcome.alreadyProcessed,
        }),
      };
    }
    return { tone: "info", text: t("portal.pipelines.run.empty") };
  }

  // Trigger the saved pipeline and report the outcome: what the sweep started (or why it started
  // nothing), then each run's terminal state. Shared by Run now and the reprocess action.
  async function reportRun(policyId: string) {
    const outcome = await triggerPipeline(policyId);
    const runIds = outcome.runIds;
    if (runIds.length === 0) {
      if (mounted.current) setRunResult(emptySweepResult(outcome));
      return;
    }
    const finals = await Promise.all(runIds.map((runId) => awaitRun(runId)));
    if (!mounted.current) return;
    const failed = finals.find((r) => r?.status === "FAILED");
    if (failed) {
      setRunResult({
        tone: "danger",
        text: t("portal.pipelines.run.failed", { error: failed.error ?? "" }),
      });
    } else if (finals.some((r) => r === null)) {
      // Gave up polling before a terminal status; the run may still finish server-side.
      setRunResult({
        tone: "warning",
        text: t("portal.pipelines.run.timeout"),
      });
    } else if (finals.every((r) => r?.status === "COMPLETED")) {
      setRunResult({
        tone: "success",
        text: t("portal.pipelines.run.completed", { count: finals.length }),
      });
    } else {
      setRunResult({ tone: "info", text: t("portal.pipelines.run.running") });
    }
  }

  async function handleRun() {
    if (running || reprocessing || !id) return;
    setRunning(true);
    setRunResult(null);
    try {
      await reportRun(id);
    } catch (e) {
      if (mounted.current)
        setRunResult({ tone: "danger", text: errorMessage(e) });
    } finally {
      if (mounted.current) setRunning(false);
    }
  }

  /**
   * Reprocess everything currently in the sources: forget which files the pipeline already handled,
   * then run at once so those files - which a normal run skips - go through now. Reports the run's
   * outcome exactly like Run now; does not touch the files themselves.
   */
  async function handleReprocessAll() {
    if (running || reprocessing || !id) return;
    setReprocessing(true);
    setRunResult(null);
    try {
      await clearProcessedHistory(id);
      await reportRun(id);
    } catch (e) {
      if (mounted.current)
        setRunResult({ tone: "danger", text: errorMessage(e) });
    } finally {
      if (mounted.current) setReprocessing(false);
    }
  }

  async function confirmDelete() {
    if (!id || deleting) return;
    setDeleting(true);
    try {
      await deletePipeline(id);
      await invalidatePipelines();
      close();
    } catch (e) {
      setError(errorMessage(e));
      setDeleting(false);
      setPendingDelete(false);
    }
  }

  if (aiAvailabilityLoading || (isEdit && !seeded)) {
    return (
      <div className="portal-builder__loading">
        <Spinner />
      </div>
    );
  }

  const chosenSteps = selectedSteps(selected);
  // One step selected means its settings; several means there is no single thing to configure.
  const selectedStep =
    chosenSteps.length === 1 ? (steps[chosenSteps[0]] ?? null) : null;

  const chosenSource = availableSources.find((s) => s.id === input.sourceId);
  const chosenDestination = writableSources.find((s) => s.id === outputIds[0]);

  /** How this input fires, in a few words, for the input node's summary line. */
  function triggerSummary(): string {
    // The editor has no trigger to schedule; it fires as each file passes through.
    if (isEditorInput)
      return runOn === "export"
        ? t("portal.pipelines.builder.runOnExport", "Every export")
        : t("portal.pipelines.builder.runOnUpload", "Every upload");
    if (input.triggerType === MANUAL)
      return t("portal.pipelines.composer.triggerManual");
    if (input.triggerType === "schedule")
      // One counted phrase per unit, so it reads "Runs every hour" / "Runs every 3 hours" rather
      // than the ungrammatical, untranslatable "Run every 1 hours".
      return t(
        `portal.pipelines.composer.runsEvery.${input.scheduleUnit.toLowerCase()}`,
        {
          count: Number(input.scheduleCount) || 1,
        },
      );
    return t(`portal.pipelines.trigger.${input.triggerType}`, {
      defaultValue: input.triggerType,
    });
  }

  /** Why a step cannot be saved yet, if anything. */
  function stepWarning(step: WorkingToolStep): string | undefined {
    if (isIntegrationStep(step)) {
      if (!stepOperation(step))
        return t("portal.pipelines.builder.chooseOperation");
      if (!integrationStepConfigured(step))
        return t("portal.pipelines.builder.chooseAccount");
      return undefined;
    }
    if (stepNeedsConfiguring(step, allTools))
      return t("portal.pipelines.builder.needsConfiguring");
    return undefined;
  }

  /** A step's one-line summary: what it will do beyond its name. */
  function stepDetail(step: WorkingToolStep): string | undefined {
    if (step.support === "unsupported")
      return t("portal.pipelines.builder.usesDefaults");
    // Integration and DocParse steps are toolId-less by design and carry their own settings UI,
    // so "unknown" here means "not a registry tool", not "we cannot drive this".
    if (isIntegrationStep(step) || isIngestStep(step)) return undefined;
    if (step.support === "unknown")
      return t("portal.pipelines.builder.unknownStep");
    return undefined;
  }

  // A run reports one step cursor, so progress reads off it: everything before the cursor is done,
  // the cursor itself is whatever the run currently is.
  function stepRunState(index: number): GraphStepContent["runState"] {
    if (!testRun) return undefined;
    const activeIndex = testRun.currentStep - 1;
    if (index < activeIndex) return "done";
    if (index > activeIndex) return undefined;
    if (testRun.status === "FAILED") return "failed";
    if (testRun.status === "COMPLETED") return "done";
    return "running";
  }

  const graphSteps: GraphStepContent[] = steps.map((step, i) => ({
    label: stepLabel(step),
    detail: stepDetail(step),
    icon: stepIcon(step),
    warning: stepWarning(step),
    inputWarning: stepInputWarning(i),
    runState: stepRunState(i),
  }));

  const definitionJson = JSON.stringify(
    {
      name: name.trim(),
      enabled,
      inputs: [{ sourceId: input.sourceId, trigger: buildTriggerFor(input) }],
      steps: steps.map((step) => serializeToolStep(step, allTools)),
      outputIds,
      routingRules,
    },
    null,
    2,
  );

  const testSummary =
    testRun === null
      ? null
      : {
          status:
            testRun.status === "FAILED"
              ? ("failed" as const)
              : testRun.status === "COMPLETED"
                ? ("completed" as const)
                : ("running" as const),
          completedSteps:
            testRun.status === "FAILED"
              ? Math.max(0, testRun.currentStep - 1)
              : testRun.currentStep,
          stepCount: testRun.stepCount,
          error: testRun.error,
          outputs: testRun.outputs ?? [],
        };

  /** The editor for whatever node is selected. Undefined when nothing is. */
  function inspectorBody() {
    if (selected === "input") {
      // Nothing to pick from yet: a dropdown of nothing helps no one, so offer only the way to make
      // the first source. The trigger has no meaning without a source either, so it waits too.
      const hasSources = sourceOptions.length > 0;
      return (
        <>
          {hasSources && (
            <>
              <FormField label={t("portal.pipelines.builder.inputSource")}>
                <div className="portal-builder__input-row">
                  <div className="portal-builder__input-field">
                    <Select
                      inputSize="sm"
                      aria-label={t("portal.pipelines.builder.inputSource")}
                      placeholder={t("portal.pipelines.builder.chooseSource")}
                      value={input.sourceId || null}
                      invalid={input.sourceId === ""}
                      onChange={(value) => changeInputSource(value ?? "")}
                      options={sourceOptions}
                    />
                  </div>
                  <ActionIcon
                    variant="tertiary"
                    className="portal-builder__source-edit"
                    aria-label={t("portal.pipelines.composer.editSource")}
                    disabled={input.sourceId === "" || isEditorInput}
                    onClick={() =>
                      setSourceModal({ open: true, sourceId: input.sourceId })
                    }
                  >
                    <Icon name="pencil" size={"1rem"} />
                  </ActionIcon>
                </div>
              </FormField>

              <PipelineInputTrigger
                input={input}
                onInputChange={updateInput}
                triggerOptions={triggerOptionsFor(input.sourceId)}
                isEditorInput={isEditorInput}
                runOn={runOn}
                onRunOnChange={setRunOn}
              />
            </>
          )}

          <Button
            variant="tertiary"
            size="sm"
            onClick={() => createSourceFor("input")}
            leftSection={<Icon name="plus" size={"1.125rem"} />}
          >
            {t("portal.sources.actions.connectSource")}
          </Button>
        </>
      );
    }

    if (selected === "output") {
      return (
        <>
          {isEditorInput && (
            <EditorDeliverySelect
              external={externalEditorOutput}
              requiresDestination={requiresDestination}
              onChange={(external) => {
                setDestinationRequested(external);
                if (!external) {
                  setOutputIds([]);
                  setRoutingRules([]);
                }
              }}
            />
          )}
          {!returnsToEditor && (
            <>
              <RoutingSection
                rules={routingRules}
                onChange={setRoutingRules}
                destinations={writableSources}
                onCreateDestination={() => createSourceFor("output")}
                canClassify={classifies}
                aiClassificationEnabled={aiClassificationEnabled}
              />
              <DestinationPicker
                label={
                  routingRules.length > 0
                    ? t(
                        "portal.pipelines.builder.routing.fallback",
                        "Everything else goes to",
                      )
                    : undefined
                }
                sources={writableSources}
                value={outputIds}
                onChange={setOutputIds}
                onCreateNew={() => createSourceFor("output")}
                onEdit={(sourceId) => setSourceModal({ open: true, sourceId })}
              />
            </>
          )}
          {vectorOutput && !vectorReady && (
            <>
              <p className="portal-builder__muted">
                {t("portal.pipelines.builder.ingest.destinationNeedsChunks")}
              </p>
              <Button
                size="sm"
                onClick={() => setSteps(prepareVectorDestination(steps))}
              >
                {t("portal.pipelines.builder.ingest.prepareDestination")}
              </Button>
            </>
          )}
        </>
      );
    }

    if (selectedStep) {
      return (
        <PipelineStepSettings
          editorInput={returnsToEditor}
          step={selectedStep}
          registry={allTools}
          onChange={(params) => updateStepParams(chosenSteps[0], params)}
          assetNames={assetNames}
          onClearBinding={(field) => clearStepBinding(chosenSteps[0], field)}
        />
      );
    }

    return undefined;
  }

  return (
    <div className="portal-builder">
      {isEdit ? (
        <PipelineEditHeader
          name={name}
          onNameChange={setName}
          icon={icon}
          onIconChange={setIcon}
          required={required}
          onRequiredChange={setRequired}
          runsOnEditor={returnsToEditor}
          canManagePolicies={canManagePolicies}
          permissionsLoading={permissionsLoading}
          enabled={enabled}
          onTogglePause={handleTogglePause}
          togglingEnabled={togglingEnabled}
          onBack={() => attemptLeave(listPath)}
          canSave={canSave}
          blockers={blockers}
          saving={submitting}
          onSave={() => save(listPath)}
          onRun={handleRun}
          running={running}
          onReprocess={handleReprocessAll}
          reprocessing={reprocessing}
          onDelete={() => setPendingDelete(true)}
        />
      ) : (
        <PipelineCreateHeader
          name={name}
          onNameChange={setName}
          icon={icon}
          onIconChange={setIcon}
          required={required}
          onRequiredChange={setRequired}
          runsOnEditor={returnsToEditor}
          canManagePolicies={canManagePolicies}
          permissionsLoading={permissionsLoading}
          canSave={canSave}
          blockers={blockers}
          saving={submitting}
          pendingCreateEnabled={pendingCreateEnabled}
          onCreate={() => submitCreate(true)}
          onCreatePaused={() => submitCreate(false)}
          onBack={() => attemptLeave(listPath)}
        />
      )}

      {error && <Banner tone="danger" description={error} />}
      {runResult && (
        <Banner
          tone={runResult.tone}
          description={<PrivateContent>{runResult.text}</PrivateContent>}
        />
      )}
      {hasUnconfiguredSteps && (
        <Banner
          tone="warning"
          description={t("portal.pipelines.builder.stepsNeedSetup", {
            tools: unconfiguredStepLabels.join(", "),
          })}
        />
      )}
      {hasIncompatibleSteps && (
        <Banner
          tone="danger"
          description={t("portal.pipelines.builder.stepsIncompatible", {
            tools: blockingSteps.join(", "),
          })}
        />
      )}

      <div className="portal-builder__grid">
        <div className="portal-builder__canvas">
          <PipelineGraphToolbar
            stepCount={steps.length}
            onTest={handleTest}
            testing={testing}
            runResult={testSummary}
            onDownloadOutput={downloadOutput}
            onViewDefinition={() => setDefinitionOpen(true)}
          />
          <PipelineGraph
            // An end is on the chain once it has been asked for or already holds a value, so a
            // loaded pipeline needs no seeding: its source and destination place themselves.
            input={
              inputAsked || inputValid
                ? {
                    label:
                      chosenSource?.name ??
                      t("portal.pipelines.builder.chooseSource"),
                    detail: chosenSource ? triggerSummary() : undefined,
                    warning: inputValid
                      ? undefined
                      : t("portal.pipelines.builder.needsSource"),
                  }
                : null
            }
            output={
              returnsToEditor
                ? {
                    label: t(
                      "portal.pipelines.builder.editorDestination",
                      "Editor",
                    ),
                    detail: t(
                      "portal.pipelines.builder.editorDestinationDetail",
                      "Replaces the file you ran it on",
                    ),
                    fixed: false,
                  }
                : isEditorInput || outputAsked || outputValid
                  ? {
                      label:
                        chosenDestination?.name ??
                        t("portal.pipelines.builder.chooseDestination"),
                      // With routing on, the destination on the node is only the fallback, so the
                      // node says how many routes come first rather than implying one endpoint.
                      detail:
                        routingRules.length > 0
                          ? t("portal.pipelines.builder.routing.nodeSummary", {
                              count: routingRules.length,
                            })
                          : undefined,
                      warning: outputValid
                        ? undefined
                        : chosenDestination && !vectorReady
                          ? t(
                              "portal.pipelines.builder.ingest.destinationNeedsChunks",
                            )
                          : t("portal.pipelines.builder.needsDestination"),
                    }
                  : null
            }
            steps={graphSteps}
            selected={selected}
            onSelect={setSelected}
            onAddEnd={addEnd}
            onRemoveEnd={removeEnd}
            onInsertStep={setPickerAt}
            onRemoveSteps={removeSteps}
            onReorderSteps={reorderSteps}
            onOpenStepError={(index) => setSelected({ steps: [index] })}
          />
        </div>

        <PipelineInspector
          title={
            selected === "input"
              ? t("portal.pipelines.builder.inputs")
              : selected === "output"
                ? t("portal.pipelines.composer.output")
                : selectedStep
                  ? stepLabel(selectedStep)
                  : undefined
          }
          icon={
            selected === "input" ? (
              <Icon name="import" size={"1.125rem"} />
            ) : selected === "output" ? (
              <Icon name="send" size={"1.125rem"} />
            ) : selectedStep ? (
              stepIcon(selectedStep)
            ) : undefined
          }
          error={
            chosenSteps.length === 1 &&
            testRun?.status === "FAILED" &&
            testRun.currentStep === chosenSteps[0]
              ? testRun.error
              : undefined
          }
          message={
            chosenSteps.length > 1
              ? t("portal.pipelines.inspector.multipleSelected", {
                  count: chosenSteps.length,
                })
              : undefined
          }
        >
          {inspectorBody()}
        </PipelineInspector>
      </div>

      <Modal
        open={pickerAt !== null}
        onClose={() => setPickerAt(null)}
        width="md"
        title={t("portal.pipelines.composer.addTool")}
        className="portal-pipelines__picker-modal"
      >
        <ToolPicker
          tools={executableTools}
          onPick={addStep}
          operations={STEP_OPERATIONS}
          onPickOperation={addOperationStep}
          precedingOutput={precedingOutput}
          unavailableReason={(tool) =>
            isClassifyTool(tool) && !aiClassificationEnabled
              ? t(
                  "portal.pipelines.builder.routing.aiToolDisabled",
                  "Unavailable until AI classification is enabled in Settings",
                )
              : undefined
          }
          onClose={() => setPickerAt(null)}
        />
      </Modal>

      <PipelineDefinitionModal
        open={definitionOpen}
        onClose={() => setDefinitionOpen(false)}
        json={definitionJson}
      />

      <Modal
        open={pendingDelete}
        onClose={() => !deleting && setPendingDelete(false)}
        width="sm"
        title={t("portal.pipelines.delete.title")}
        footer={
          <div className="portal-builder__composer-footer">
            <Button
              variant="tertiary"
              size="sm"
              disabled={deleting}
              onClick={() => setPendingDelete(false)}
            >
              {t("portal.pipelines.delete.cancel")}
            </Button>
            <Button
              size="sm"
              accent="danger"
              loading={deleting}
              onClick={confirmDelete}
            >
              {t("portal.pipelines.delete.confirm")}
            </Button>
          </div>
        }
      >
        <p>{t("portal.pipelines.delete.body", { name: name || "" })}</p>
      </Modal>

      <Modal
        open={pendingNav !== null}
        onClose={() => !submitting && setPendingNav(null)}
        width="sm"
        title={t("portal.pipelines.builder.unsavedTitle")}
        footer={
          <div className="portal-builder__composer-footer">
            <Button
              variant="tertiary"
              size="sm"
              disabled={submitting}
              onClick={() => setPendingNav(null)}
            >
              {t("portal.pipelines.builder.keepEditing")}
            </Button>
            <div style={{ display: "flex", gap: "0.5rem" }}>
              <Button
                variant="secondary"
                size="sm"
                accent="danger"
                disabled={submitting}
                onClick={() => {
                  const target = pendingNav;
                  setPendingNav(null);
                  if (target) navigate(target);
                }}
              >
                {t("portal.pipelines.builder.discard")}
              </Button>
              <Button
                size="sm"
                loading={submitting}
                disabled={!canSave}
                onClick={() => {
                  const target = pendingNav;
                  setPendingNav(null);
                  if (target) void save(target);
                }}
              >
                {t("portal.pipelines.composer.save")}
              </Button>
            </div>
          </div>
        }
      >
        <p>{t("portal.pipelines.builder.unsavedBody")}</p>
      </Modal>

      <SourceModal
        direction={sourceModal.direction}
        open={sourceModal.open}
        sourceId={sourceModal.sourceId}
        onCreated={(source) => {
          if (!source.id) return;
          if (sourceModal.direction === "input" && isReadableSource(source)) {
            changeInputSource(source.id);
          } else if (
            sourceModal.direction === "output" &&
            isWritableSource(source)
          ) {
            setOutputIds([source.id]);
          }
        }}
        onClose={() => setSourceModal({ open: false, sourceId: null })}
      />
    </div>
  );
}