Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

feat: ship ingest review UI with settings, Docling preview, and chunk search (#2115)

Wallgaua2ddda82bff5
diff --git a/frontend/app/api/queries/useFileScopedChunksQuery.ts b/frontend/app/api/queries/useFileScopedChunksQuery.ts
new file mode 100644
index 000000000..ec2389bef
--- /dev/null
+++ b/frontend/app/api/queries/useFileScopedChunksQuery.ts
@@ -0,0 +1,21 @@
+import {
+ EMPTY_SEARCH_RESULT,
+ type File,
+ type SearchResult,
+ useGetSearchQuery,
+} from "@/app/api/queries/useGetSearchQuery";
+import { fileScopedSearchQueryData } from "@/lib/file-chunks";
+
+/** Loads every chunk for one filename (shared by chunks page + FileChunksPanel). */
+export function useFileScopedChunksQuery(filename: string | null | undefined) {
+ const queryData = filename ? fileScopedSearchQueryData(filename) : null;
+ const { data = EMPTY_SEARCH_RESULT, isFetching } = useGetSearchQuery(
+ "*",
+ queryData,
+ { enabled: Boolean(filename) },
+ );
+ const file = (data as SearchResult).files.find(
+ (entry: File) => entry.filename === filename,
+ );
+ return { file, isFetching };
+}
diff --git a/frontend/app/api/queries/useIngestPreviewQuery.ts b/frontend/app/api/queries/useIngestPreviewQuery.ts
new file mode 100644
index 000000000..2b8ce9b89
--- /dev/null
+++ b/frontend/app/api/queries/useIngestPreviewQuery.ts
@@ -0,0 +1,152 @@
+import { type QueryKey, useQuery, useQueryClient } from "@tanstack/react-query";
+
+export interface DoclingPreviewStats {
+ page_count: number;
+ text_count: number;
+ table_count: number;
+ picture_count: number;
+}
+
+export interface DoclingPreviewResponse {
+ task_id: string;
+ document: Record<string, unknown>;
+ stats: DoclingPreviewStats;
+ expires_at: number;
+ document_id?: string;
+ file_path?: string;
+ filename?: string;
+}
+
+/** A single indexed chunk from the preview index-proof endpoint. */
+export interface IndexProofChunk {
+ chunk_id: string;
+ page?: number | null;
+ text_preview: string;
+ char_count: number;
+}
+
+/** Response of GET /ingest/preview/{task_id}/index-proof. */
+export interface IndexProofResponse {
+ task_id: string;
+ ready: boolean;
+ phase?: string;
+ chunk_count: number;
+ chunks_returned?: number;
+ chunks_truncated?: boolean;
+ embedding_model?: string;
+ embedding_dimensions?: number;
+ chunks: IndexProofChunk[];
+ document_id?: string | null;
+}
+
+/**
+ * Index-proof can flip to ready without a task phase change, so it still
+ * polls. Docling preview does not — it refetches on task phase / retry.
+ */
+const INDEX_PROOF_POLL_INTERVAL_MS = 1500;
+const INDEX_PROOF_MAX_POLLS = 60;
+
+export const ingestPreviewQueryKeys = {
+ docling: (taskId: string | null, filePath?: string | null) =>
+ ["ingest-preview", "docling", taskId, filePath ?? null] as const,
+ indexProof: (taskId: string | null, filePath?: string | null) =>
+ ["ingest-preview", "index-proof", taskId, filePath ?? null] as const,
+};
+
+function withFileParam(path: string, filePath?: string | null): string {
+ return filePath ? `${path}?file=${encodeURIComponent(filePath)}` : path;
+}
+
+async function fetchPreviewJson<T>(
+ path: string,
+ filePath: string | null | undefined,
+ options: { notFoundAsNull: true },
+): Promise<T | null>;
+async function fetchPreviewJson<T>(
+ path: string,
+ filePath?: string | null,
+ options?: { notFoundAsNull?: false },
+): Promise<T>;
+async function fetchPreviewJson<T>(
+ path: string,
+ filePath?: string | null,
+ options?: { notFoundAsNull?: boolean },
+): Promise<T | null> {
+ const response = await fetch(withFileParam(path, filePath));
+ if (options?.notFoundAsNull && response.status === 404) {
+ return null;
+ }
+ if (!response.ok) {
+ throw new Error(`Preview unavailable (${response.status})`);
+ }
+ return response.json() as Promise<T>;
+}
+
+/**
+ * Fetch Docling layout cache once. 404 → null ("not cached yet").
+ * No interval polling — callers refetch when the ingest task phase advances
+ * or when the user retries.
+ */
+export function useDoclingPreviewQuery(
+ taskId: string | null,
+ enabled: boolean,
+ filePath?: string | null,
+) {
+ const queryClient = useQueryClient();
+
+ return useQuery(
+ {
+ queryKey: ingestPreviewQueryKeys.docling(taskId, filePath),
+ queryFn: () =>
+ fetchPreviewJson<DoclingPreviewResponse>(
+ `/api/ingest/preview/${taskId}/docling`,
+ filePath,
+ { notFoundAsNull: true },
+ ),
+ enabled: enabled && !!taskId,
+ // Keep large documents cached once loaded; null/404 stays stale so a
+ // later phase-driven refetch can replace it.
+ staleTime: (q) => (q.state.data?.document ? Number.POSITIVE_INFINITY : 0),
+ retry: 1,
+ refetchOnWindowFocus: false,
+ },
+ queryClient,
+ );
+}
+
+/**
+ * Poll index-proof until chunks land (keyed by task + file).
+ *
+ * "Not ready yet" is HTTP 200 with `ready: false` — keep polling via isDone.
+ * 404 (missing task/file, preview disabled) throws and stops polling; that is
+ * intentional, unlike Docling preview where 404 means "still parsing".
+ */
+export function useIndexProofQuery(
+ taskId: string | null,
+ enabled: boolean,
+ filePath?: string | null,
+) {
+ const queryClient = useQueryClient();
+
+ return useQuery(
+ {
+ queryKey: ingestPreviewQueryKeys.indexProof(taskId, filePath) as QueryKey,
+ queryFn: () =>
+ fetchPreviewJson<IndexProofResponse>(
+ `/api/ingest/preview/${taskId}/index-proof`,
+ filePath,
+ ),
+ enabled: enabled && !!taskId,
+ staleTime: 5_000,
+ refetchInterval: (query) => {
+ if (query.state.error) return false;
+ if (query.state.data?.ready) return false;
+ if (query.state.dataUpdateCount >= INDEX_PROOF_MAX_POLLS) return false;
+ return INDEX_PROOF_POLL_INTERVAL_MS;
+ },
+ retry: false,
+ refetchOnWindowFocus: false,
+ },
+ queryClient,
+ );
+}
diff --git a/frontend/app/knowledge/chunks/page.tsx b/frontend/app/knowledge/chunks/page.tsx
index 3edaf2c68..5eb3f3ef8 100644
--- a/frontend/app/knowledge/chunks/page.tsx
+++ b/frontend/app/knowledge/chunks/page.tsx
@@ -1,115 +1,24 @@
"use client";
-import { ArrowLeft, Check, Copy, Loader2, Search, X } from "lucide-react";
+import { ArrowLeft, Loader2, Search } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
-import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
-// import { Label } from "@/components/ui/label";
-// import { Checkbox } from "@/components/ui/checkbox";
-import { KnowledgeSearchInput } from "@/components/knowledge-search-input";
-// import { Label } from "@/components/ui/label";
-// import { Checkbox } from "@/components/ui/checkbox";
+import { Suspense } from "react";
+import { useFileScopedChunksQuery } from "@/app/api/queries/useFileScopedChunksQuery";
+import { FileChunksPanel } from "@/components/file-chunks-panel";
import { ProtectedRoute } from "@/components/protected-route";
-import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
-import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
-import { trackButton } from "@/lib/analytics";
import { formatFileSize, getFileTypeLabel } from "@/lib/file-format";
-import {
- type ChunkResult,
- EMPTY_SEARCH_RESULT,
- type File,
- type SearchResult,
- useGetSearchQuery,
-} from "../../api/queries/useGetSearchQuery";
function ChunksPageContent() {
const router = useRouter();
const searchParams = useSearchParams();
- const { parsedFilterData, queryOverride } = useKnowledgeFilter();
const filename = searchParams.get("filename");
- const [chunks, setChunks] = useState<ChunkResult[]>([]);
- // const [chunksFilteredByQuery, setChunksFilteredByQuery] = useState<
- // ChunkResult[]
- // >([]);
- // const [selectedChunks, setSelectedChunks] = useState<Set<number>>(new Set());
- const [activeCopiedChunkIndex, setActiveCopiedChunkIndex] = useState<
- number | null
- >(null);
-
- // Calculate average chunk length
- const averageChunkLength = useMemo(
- () =>
- chunks.reduce((acc, chunk) => acc + chunk.text.length, 0) /
- chunks.length || 0,
- [chunks],
- );
-
- // const [selectAll, setSelectAll] = useState(false);
-
- // Use the same search query as the knowledge page, but we'll filter for the specific file
- const { data = EMPTY_SEARCH_RESULT, isFetching } = useGetSearchQuery(
- queryOverride,
- parsedFilterData,
- );
- const searchFiles = (data as SearchResult).files;
-
- const handleCopy = useCallback((text: string, index: number) => {
- trackButton({
- CTA: "Copy Chunk Text",
- elementId: "copy-chunk-button",
- namespace: "knowledge",
- });
- navigator.clipboard.writeText(text.trim().replace(/[\n\r\t]/gm, ""));
- setActiveCopiedChunkIndex(index);
- setTimeout(() => setActiveCopiedChunkIndex(null), 10 * 1000); // 10 seconds
- }, []);
-
- const fileData = searchFiles.find((file: File) => file.filename === filename);
-
- // Extract chunks for the specific file
- useEffect(() => {
- if (!filename || !searchFiles.length) {
- setChunks([]);
- return;
- }
-
- setChunks(
- fileData?.chunks?.map((chunk, i) => ({ ...chunk, index: i + 1 })) || [],
- );
- }, [searchFiles, filename, fileData?.chunks]);
-
- // Set selected state for all checkboxes when selectAll changes
- // useEffect(() => {
- // if (selectAll) {
- // setSelectedChunks(new Set(chunks.map((_, index) => index)));
- // } else {
- // setSelectedChunks(new Set());
- // }
- // }, [selectAll, setSelectedChunks, chunks]);
-
- const handleBack = useCallback(() => {
- router.push("/knowledge");
- }, [router]);
-
- // const handleChunkCardCheckboxChange = useCallback(
- // (index: number) => {
- // setSelectedChunks((prevSelected) => {
- // const newSelected = new Set(prevSelected);
- // if (newSelected.has(index)) {
- // newSelected.delete(index);
- // } else {
- // newSelected.add(index);
- // }
- // return newSelected;
- // });
- // },
- // [setSelectedChunks]
- // );
+ const { file: fileData } = useFileScopedChunksQuery(filename);
if (!filename) {
return (
@@ -125,126 +34,42 @@ function ChunksPageContent() {
);
}
+ const chunks = fileData?.chunks ?? [];
+ const chunkCount = chunks.length;
+ const averageChunkLength =
+ chunkCount === 0
+ ? 0
+ : chunks.reduce((acc, chunk) => acc + chunk.text.length, 0) / chunkCount;
+
+ const hasAccessControl =
+ Boolean(fileData?.owner) ||
+ (fileData?.allowed_users?.length ?? 0) > 0 ||
+ (fileData?.allowed_groups?.length ?? 0) > 0;
+
return (
<div className="flex flex-col h-full">
- {/* Header */}
<div className="flex flex-col mb-6">
<div className="flex items-center gap-3 mb-6">
<Button
variant="ghost"
- onClick={handleBack}
+ onClick={() => router.push("/knowledge")}
size="sm"
className="max-w-8 max-h-8 -m-2"
>
<ArrowLeft size={24} />
</Button>
<h1 className="text-lg font-semibold">
- {/* Removes file extension from filename */}
{filename.replace(/\.[^/.]+$/, "")}
</h1>
</div>
- <div className="flex flex-1">
- <KnowledgeSearchInput />
- {/* <div className="flex items-center pl-4 gap-2">
- <Checkbox
- id="selectAllChunks"
- checked={selectAll}
- onCheckedChange={handleSelectAll =>
- setSelectAll(!!handleSelectAll)
- }
- />
- <Label
- htmlFor="selectAllChunks"
- className="font-medium text-muted-foreground whitespace-nowrap cursor-pointer"
- >
- Select all
- </Label>
- </div> */}
- </div>
</div>
<div className="grid gap-6 grid-cols-1 lg:grid-cols-[3fr_1fr]">
- {/* Content Area */}
<div className="row-start-2 lg:row-start-1">
- {isFetching ? (
- <div className="flex items-center justify-center h-64">
- <div className="text-center">
- <Loader2 className="h-12 w-12 mx-auto mb-4 text-muted-foreground/50 animate-spin" />
- <p className="text-lg text-muted-foreground">
- Loading chunks...
- </p>
- </div>
- </div>
- ) : chunks.length === 0 ? (
- <div className="flex items-center justify-center h-64">
- <div className="text-center">
- <p className="text-xl font-semibold mb-2">No knowledge</p>
- <p className="text-sm text-secondary-foreground">
- Clear the knowledge filter or return to the knowledge page
- </p>
- </div>
- </div>
- ) : (
- <div className="space-y-4 pb-6">
- {chunks.map((chunk, index) => (
- <div
- key={chunk.filename + index}
- className="bg-muted rounded-lg p-4 border border-border/50"
- >
- <div className="flex items-center justify-between mb-2">
- <div className="flex items-center gap-3">
- {/* <div>
- <Checkbox
- checked={selectedChunks.has(index)}
- onCheckedChange={() =>
- handleChunkCardCheckboxChange(index)
- }
- />
- </div> */}
- <span className="text-sm font-bold">
- Chunk {chunk.index}
- </span>
- <Badge variant="secondary">
- {chunk.text.length} chars
- </Badge>
- <div className="py-1">
- <Button
- onClick={() => handleCopy(chunk.text, index)}
- variant="ghost"
- size="sm"
- >
- {activeCopiedChunkIndex === index ? (
- <Check className="text-muted-foreground" />
- ) : (
- <Copy className="text-muted-foreground" />
- )}
- </Button>
- </div>
- </div>
-
- <Badge variant="secondary">
- {chunk.score.toFixed(2)} score
- </Badge>
-
- {/* TODO: Update to use active toggle */}
- {/* <span className="px-2 py-1 text-green-500">
- <Switch
- className="ml-2 bg-green-500"
- checked={true}
- />
- Active
- </span> */}
- </div>
- <blockquote className="text-sm text-muted-foreground leading-relaxed ml-1.5">
- {chunk.text}
- </blockquote>
- </div>
- ))}
- </div>
- )}
+ <FileChunksPanel filename={filename} />
</div>
- {/* Right panel - Summary (TODO), Technical details, */}
- {chunks.length > 0 && (
+
+ {chunkCount > 0 && (
<div className="min-w-[200px]">
<div className="mb-8">
<h2 className="text-xl font-semibold mb-4">Technical details</h2>
@@ -254,7 +79,7 @@ function ChunksPageContent() {
Total chunks
</dt>
<dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
- {chunks.length}
+ {chunkCount}
</dd>
</div>
<div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
@@ -265,17 +90,6 @@ function ChunksPageContent() {
{averageChunkLength.toFixed(0)} chars
</dd>
</div>
- {/* TODO: Uncomment after data is available */}
- {/* <div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
- <dt className="text-sm/6 text-muted-foreground">Process time</dt>
- <dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
- </dd>
- </div>
- <div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
- <dt className="text-sm/6 text-muted-foreground">Model</dt>
- <dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
- </dd>
- </div> */}
</dl>
</div>
<div className="mb-4">
@@ -283,12 +97,6 @@ function ChunksPageContent() {
Original document
</h2>
<dl>
- {/* <div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
- <dt className="text-sm/6 text-muted-foreground">Name</dt>
- <dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
- {fileData?.filename}
- </dd>
- </div> */}
<div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
<dt className="text-sm/6 text-muted-foreground">Type</dt>
<dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
@@ -301,35 +109,9 @@ function ChunksPageContent() {
{fileData?.size ? formatFileSize(fileData.size) : "Unknown"}
</dd>
</div>
- {/* <div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
- <dt className="text-sm/6 text-muted-foreground">Uploaded</dt>
- <dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
- N/A
- </dd>
- </div> */}
- {/* TODO: Uncomment after data is available */}
- {/* <div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
- <dt className="text-sm/6 text-muted-foreground">Source</dt>
- <dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0"></dd>
- </div> */}
- {/* <div className="sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0 mb-2.5">
- <dt className="text-sm/6 text-muted-foreground">Updated</dt>
- <dd className="mt-1 text-sm/6 text-gray-800 dark:text-gray-100 sm:col-span-2 sm:mt-0">
- N/A
- </dd>
- </div> */}
</dl>
</div>
- {(() => {
- const hasOwner = Boolean(fileData?.owner);
- const hasAllowedUsers =
- (fileData?.allowed_users?.length ?? 0) > 0;
- const hasAllowedGroups =
- (fileData?.allowed_groups?.length ?? 0) > 0;
- const showAccessControl =
- hasOwner || hasAllowedUsers || hasAllowedGroups;
- return showAccessControl;
- })() ? (
+ {hasAccessControl && (
<div className="mb-4">
<h2 className="text-xl font-semibold mt-2 mb-3">
Access Control
@@ -416,7 +198,7 @@ function ChunksPageContent() {
)}
</dl>
</div>
- ) : null}
+ )}
</div>
)}
</div>
diff --git a/frontend/app/onboarding/_components/onboarding-upload.tsx b/frontend/app/onboarding/_components/onboarding-upload.tsx
index 554506b80..fe4a46291 100644
--- a/frontend/app/onboarding/_components/onboarding-upload.tsx
+++ b/frontend/app/onboarding/_components/onboarding-upload.tsx
@@ -1,14 +1,28 @@
import { X } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
-import { type ChangeEvent, useEffect, useRef, useState } from "react";
+import {
+ type ChangeEvent,
+ useCallback,
+ useEffect,
+ useReducer,
+ useRef,
+} from "react";
import { toast } from "sonner";
import { useCreateFilter } from "@/app/api/mutations/useCreateFilter";
import { useUpdateOnboardingStateMutation } from "@/app/api/mutations/useUpdateOnboardingStateMutation";
import { useGetNudgesQuery } from "@/app/api/queries/useGetNudgesQuery";
import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery";
import { AnimatedProviderSteps } from "@/app/onboarding/_components/animated-provider-steps";
+import { IngestReviewDialog } from "@/components/ingest-review";
import { Button } from "@/components/ui/button";
+import { useAuth } from "@/contexts/auth-context";
+import { useIsCloudBrand } from "@/contexts/brand-context";
import { trackButton } from "@/lib/analytics";
+import {
+ EMPTY_PREVIEW,
+ isIngestPreviewEnabled,
+ type PreviewDialogState,
+} from "@/lib/ingest-preview";
import { SUPPORTED_EXTENSIONS } from "@/lib/supported-file-types";
import { uploadFile } from "@/lib/upload-utils";
@@ -16,27 +30,162 @@ interface OnboardingUploadProps {
onComplete: () => void;
}
+const STEP_LIST = [
+ "Uploading your document",
+ "Generating embeddings",
+ "Ingesting document",
+ "Processing your document",
+];
+
+type UploadState = {
+ isUploading: boolean;
+ currentStep: number | null;
+ uploadedFilename: string | null;
+ uploadedTaskId: string | null;
+ shouldCreateFilter: boolean;
+ isCreatingFilter: boolean;
+ ingestionReady: boolean;
+ error: string | null;
+ preview: PreviewDialogState;
+};
+
+type UploadAction =
+ | { type: "start_upload"; preview: PreviewDialogState }
+ | { type: "set_step"; step: number | null }
+ | { type: "set_preview"; preview: PreviewDialogState }
+ | {
+ type: "upload_succeeded";
+ taskId: string | null;
+ /** null = leave existing preview unchanged. */
+ preview: PreviewDialogState | null;
+ filename: string | null;
+ createFilter: boolean;
+ }
+ | { type: "upload_failed"; error: string }
+ | { type: "upload_finished" }
+ | { type: "ingestion_failed"; error: string }
+ | { type: "begin_create_filter"; filename: string }
+ | { type: "finish_create_filter" }
+ | { type: "mark_ingestion_ready" };
+
+const initialUploadState: UploadState = {
+ isUploading: false,
+ currentStep: null,
+ uploadedFilename: null,
+ uploadedTaskId: null,
+ shouldCreateFilter: false,
+ isCreatingFilter: false,
+ ingestionReady: false,
+ error: null,
+ preview: EMPTY_PREVIEW,
+};
+
+function uploadReducer(state: UploadState, action: UploadAction): UploadState {
+ switch (action.type) {
+ case "start_upload":
+ return {
+ ...state,
+ isUploading: true,
+ error: null,
+ ingestionReady: false,
+ // Always replace — callers pass EMPTY_PREVIEW when preview is disabled
+ // so a prior open review cannot stick across uploads.
+ preview: action.preview,
+ };
+ case "set_step":
+ return { ...state, currentStep: action.step };
+ case "set_preview":
+ return { ...state, preview: action.preview };
+ case "upload_succeeded":
+ return {
+ ...state,
+ uploadedTaskId: action.taskId ?? state.uploadedTaskId,
+ preview: action.preview ?? state.preview,
+ uploadedFilename: action.filename ?? state.uploadedFilename,
+ shouldCreateFilter: action.createFilter
+ ? true
+ : state.shouldCreateFilter,
+ };
+ case "upload_failed":
+ return {
+ ...state,
+ error: action.error,
+ preview: EMPTY_PREVIEW,
+ currentStep: null,
+ uploadedTaskId: null,
+ };
+ case "upload_finished":
+ return { ...state, isUploading: false };
+ case "ingestion_failed":
+ return {
+ ...state,
+ ingestionReady: false,
+ error: action.error,
+ currentStep: null,
+ uploadedTaskId: null,
+ preview: EMPTY_PREVIEW,
+ };
+ case "begin_create_filter":
+ return {
+ ...state,
+ shouldCreateFilter: false,
+ uploadedFilename: null,
+ isCreatingFilter: true,
+ currentStep: STEP_LIST.length,
+ };
+ case "finish_create_filter":
+ return {
+ ...state,
+ isCreatingFilter: false,
+ ingestionReady: true,
+ };
+ case "mark_ingestion_ready":
+ return {
+ ...state,
+ currentStep: STEP_LIST.length,
+ ingestionReady: true,
+ };
+ default:
+ return state;
+ }
+}
+
const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const completeTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
- const [isUploading, setIsUploading] = useState(false);
- const [currentStep, setCurrentStep] = useState<number | null>(null);
- const [uploadedFilename, setUploadedFilename] = useState<string | null>(null);
- const [uploadedTaskId, setUploadedTaskId] = useState<string | null>(null);
- const [shouldCreateFilter, setShouldCreateFilter] = useState(false);
- const [isCreatingFilter, setIsCreatingFilter] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ const didCompleteRef = useRef(false);
+ const onCompleteRef = useRef(onComplete);
+ onCompleteRef.current = onComplete;
+ const [state, dispatch] = useReducer(uploadReducer, initialUploadState);
+ const {
+ isUploading,
+ currentStep,
+ uploadedFilename,
+ uploadedTaskId,
+ shouldCreateFilter,
+ isCreatingFilter,
+ ingestionReady,
+ error,
+ preview,
+ } = state;
+
+ const { runMode } = useAuth();
+ const isCloudBrand = useIsCloudBrand();
+ const ingestPreviewEnabled = isIngestPreviewEnabled(runMode, {
+ isCloudBrand,
+ });
+ const ingestPreviewEnabledRef = useRef(ingestPreviewEnabled);
+ ingestPreviewEnabledRef.current = ingestPreviewEnabled;
+ const previewOpenRef = useRef(preview.open);
+ previewOpenRef.current = preview.open;
+ const ingestionReadyRef = useRef(ingestionReady);
+ ingestionReadyRef.current = ingestionReady;
+ const isCreatingFilterRef = useRef(isCreatingFilter);
+ isCreatingFilterRef.current = isCreatingFilter;
const createFilterMutation = useCreateFilter();
const updateOnboardingMutation = useUpdateOnboardingStateMutation();
- const STEP_LIST = [
- "Uploading your document",
- "Generating embeddings",
- "Ingesting document",
- "Processing your document",
- ];
-
// Query tasks to track completion
const { data: tasks } = useGetTasksQuery({
enabled: currentStep !== null, // Only poll when upload has started
@@ -45,11 +194,27 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
const { refetch: refetchNudges } = useGetNudgesQuery(null);
- useEffect(() => () => clearTimeout(completeTimeoutRef.current), []);
-
- // Monitor tasks and call onComplete when file processing is done
+ const cancelScheduledComplete = useCallback(() => {
+ clearTimeout(completeTimeoutRef.current);
+ completeTimeoutRef.current = undefined;
+ }, []);
+
+ // Schedule advancing to chat from the completion path itself (not a follow-up
+ // effect watching ingestionReady). Delay while the review dialog is open.
+ const scheduleComplete = useCallback(() => {
+ if (didCompleteRef.current || completeTimeoutRef.current) return;
+ if (ingestPreviewEnabledRef.current && previewOpenRef.current) return;
+
+ const timeoutId = setTimeout(() => {
+ didCompleteRef.current = true;
+ completeTimeoutRef.current = undefined;
+ onCompleteRef.current();
+ }, 1000);
+ completeTimeoutRef.current = timeoutId;
+ }, []);
+
+ // Monitor tasks and mark ingestion ready when file processing is done
useEffect(() => {
- let cancelled = false;
if (currentStep === null || !tasks || !uploadedTaskId) {
return;
}
@@ -97,26 +262,20 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
}
}
- clearTimeout(completeTimeoutRef.current);
- setError(errorMessage);
- setCurrentStep(null);
- setUploadedTaskId(null);
+ cancelScheduledComplete();
+ didCompleteRef.current = false;
+ dispatch({ type: "ingestion_failed", error: errorMessage });
return;
}
- // If task is completed or has processed files, complete the onboarding step
+ // If task is completed or has processed files, prepare to finish the step
if (!isTaskActive || (matchingTask.processed_files ?? 0) > 0) {
- // Set to final step to show "Done"
- setCurrentStep(STEP_LIST.length);
-
// Create knowledge filter for uploaded document if requested
// Guard against race condition: only create if not already creating
if (shouldCreateFilter && uploadedFilename && !isCreatingFilter) {
- // Reset flags immediately (synchronously) to prevent duplicate creation
- setShouldCreateFilter(false);
const filename = uploadedFilename;
- setUploadedFilename(null);
- setIsCreatingFilter(true);
+ // Reset flags immediately (synchronously) to prevent duplicate creation
+ dispatch({ type: "begin_create_filter", filename });
// Get display name from filename (remove extension for cleaner name)
const displayName = filename.includes(".")
@@ -152,43 +311,35 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
});
}
})
- .catch((error) => {
- console.error("Failed to create knowledge filter:", error);
+ .catch((filterError) => {
+ console.error("Failed to create knowledge filter:", filterError);
})
.finally(() => {
- setIsCreatingFilter(false);
+ // Always mark ready — task-poll effect re-runs must not leave us stuck
+ // with Done steps but ingestionReady never set.
refetchNudges();
-
- if (!cancelled && !completeTimeoutRef.current) {
- completeTimeoutRef.current = setTimeout(() => {
- onComplete();
- }, 1000);
- }
+ dispatch({ type: "finish_create_filter" });
+ scheduleComplete();
});
- } else if (!isCreatingFilter && !completeTimeoutRef.current) {
+ } else if (!isCreatingFilter && !ingestionReady) {
refetchNudges();
-
- completeTimeoutRef.current = setTimeout(() => {
- onComplete();
- }, 1000);
+ dispatch({ type: "mark_ingestion_ready" });
+ scheduleComplete();
}
}
-
- return () => {
- cancelled = true;
- };
}, [
tasks,
currentStep,
- onComplete,
refetchNudges,
shouldCreateFilter,
uploadedFilename,
uploadedTaskId,
createFilterMutation,
isCreatingFilter,
+ ingestionReady,
updateOnboardingMutation.mutateAsync,
- STEP_LIST.length,
+ cancelScheduledComplete,
+ scheduleComplete,
]);
const resetFileInput = () => {
@@ -207,32 +358,62 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
};
const performUpload = async (file: File) => {
- setIsUploading(true);
- setError(null);
+ didCompleteRef.current = false;
+ cancelScheduledComplete();
+ // Onboarding always opens the review when the feature flag is on.
+ dispatch({
+ type: "start_upload",
+ preview: ingestPreviewEnabled
+ ? {
+ open: true,
+ taskIds: [],
+ filename: file.name,
+ files: [file],
+ }
+ : EMPTY_PREVIEW,
+ });
try {
- setCurrentStep(0);
- const result = await uploadFile(file, true, true); // Pass createFilter=true
+ dispatch({ type: "set_step", step: 0 });
+ const result = await uploadFile(
+ file,
+ true,
+ true,
+ undefined,
+ ingestPreviewEnabled,
+ );
- // Store task ID to track the specific upload task
+ let nextPreview: PreviewDialogState | null = null;
if (result.taskId) {
- setUploadedTaskId(result.taskId);
+ if (result.previewMode) {
+ nextPreview = {
+ open: true,
+ taskIds: [result.taskId],
+ filename: file.name,
+ files: [file],
+ };
+ } else if (ingestPreviewEnabled) {
+ nextPreview = EMPTY_PREVIEW;
+ }
}
- // Store filename and createFilter flag in state to create filter after ingestion succeeds
- if (result.createFilter && result.filename) {
- setUploadedFilename(result.filename);
- setShouldCreateFilter(true);
- }
+ dispatch({
+ type: "upload_succeeded",
+ taskId: result.taskId ?? null,
+ preview: nextPreview,
+ filename:
+ result.createFilter && result.filename ? result.filename : null,
+ createFilter: Boolean(result.createFilter && result.filename),
+ });
// Move to processing step - task monitoring will handle completion
setTimeout(() => {
- setCurrentStep(1);
+ dispatch({ type: "set_step", step: 1 });
}, 1500);
- } catch (error) {
+ } catch (uploadError) {
const errorMessage =
- error instanceof Error ? error.message : "Upload failed";
+ uploadError instanceof Error ? uploadError.message : "Upload failed";
console.error("Upload failed", errorMessage);
- setError(errorMessage);
+ dispatch({ type: "upload_failed", error: errorMessage });
// Dispatch event that chat context can listen to
// This avoids circular dependency issues
@@ -249,12 +430,8 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
description: errorMessage,
duration: 5000,
});
-
- // Reset on error
- setCurrentStep(null);
- setUploadedTaskId(null);
} finally {
- setIsUploading(false);
+ dispatch({ type: "upload_finished" });
}
};
@@ -267,10 +444,10 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
try {
await performUpload(selectedFile);
- } catch (error) {
+ } catch (prepareError) {
console.error(
"Unable to prepare file for upload",
- (error as Error).message,
+ (prepareError as Error).message,
);
} finally {
resetFileInput();
@@ -278,66 +455,90 @@ const OnboardingUpload = ({ onComplete }: OnboardingUploadProps) => {
};
return (
- <AnimatePresence mode="wait">
- {currentStep === null ? (
- <motion.div
- key="user-ingest"
- initial={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: -24 }}
- transition={{ duration: 0.4, ease: "easeInOut" }}
- >
- <AnimatePresence mode="wait">
- {error && (
- <motion.div
- key="error"
- initial={{ opacity: 1, y: 0, height: "auto" }}
- exit={{ opacity: 0, y: -10, height: 0 }}
- >
- <div className="pb-6 flex items-center gap-4">
- <X className="w-4 h-4 text-destructive shrink-0" />
- <span
- data-testid="onboarding-upload-error"
- className="text-mmd text-muted-foreground"
- >
- {error}
- </span>
- </div>
- </motion.div>
- )}
- </AnimatePresence>
- <Button
- size="sm"
- variant="outline"
- data-testid="upload-button"
- onClick={handleUploadClick}
- disabled={isUploading}
+ <>
+ <AnimatePresence mode="wait">
+ {currentStep === null ? (
+ <motion.div
+ key="user-ingest"
+ initial={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: -24 }}
+ transition={{ duration: 0.4, ease: "easeInOut" }}
+ >
+ <AnimatePresence mode="wait">
+ {error && (
+ <motion.div
+ key="error"
+ initial={{ opacity: 1, y: 0, height: "auto" }}
+ exit={{ opacity: 0, y: -10, height: 0 }}
+ >
+ <div className="pb-6 flex items-center gap-4">
+ <X className="w-4 h-4 text-destructive shrink-0" />
+ <span
+ data-testid="onboarding-upload-error"
+ className="text-mmd text-muted-foreground"
+ >
+ {error}
+ </span>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ <Button
+ size="sm"
+ variant="outline"
+ data-testid="upload-button"
+ onClick={handleUploadClick}
+ disabled={isUploading}
+ >
+ <div>{isUploading ? "Uploading..." : "Add a document"}</div>
+ </Button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ onChange={handleFileChange}
+ className="hidden"
+ accept={SUPPORTED_EXTENSIONS.join(",")}
+ />
+ </motion.div>
+ ) : (
+ <motion.div
+ key="ingest-steps"
+ initial={{ opacity: 0, y: 24 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.4, ease: "easeInOut" }}
>
- <div>{isUploading ? "Uploading..." : "Add a document"}</div>
- </Button>
- <input
- ref={fileInputRef}
- type="file"
- onChange={handleFileChange}
- className="hidden"
- accept={SUPPORTED_EXTENSIONS.join(",")}
- />
- </motion.div>
- ) : (
- <motion.div
- key="ingest-steps"
- initial={{ opacity: 0, y: 24 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.4, ease: "easeInOut" }}
- >
- <AnimatedProviderSteps
- currentStep={currentStep}
- setCurrentStep={setCurrentStep}
- isCompleted={false}
- steps={STEP_LIST}
- />
- </motion.div>
- )}
- </AnimatePresence>
+ <AnimatedProviderSteps
+ currentStep={currentStep}
+ setCurrentStep={(step) => dispatch({ type: "set_step", step })}
+ isCompleted={false}
+ steps={STEP_LIST}
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ <IngestReviewDialog
+ open={preview.open}
+ onOpenChange={(open) => {
+ dispatch({
+ type: "set_preview",
+ preview: open ? { ...preview, open } : EMPTY_PREVIEW,
+ });
+ // Preview was holding completion — advance once the dialog closes.
+ if (
+ !open &&
+ ingestionReadyRef.current &&
+ !isCreatingFilterRef.current
+ ) {
+ previewOpenRef.current = false;
+ scheduleComplete();
+ }
+ }}
+ taskIds={preview.taskIds}
+ previewFiles={preview.files}
+ showAutoOpenFooter
+ />
+ </>
);
};
diff --git a/frontend/app/settings/[tab]/page.tsx b/frontend/app/settings/[tab]/page.tsx
index daa701469..75dbf0807 100644
--- a/frontend/app/settings/[tab]/page.tsx
+++ b/frontend/app/settings/[tab]/page.tsx
@@ -11,6 +11,7 @@ import { AgentSettingsSection } from "../_components/agent-settings-section";
import { ApiKeysSection } from "../_components/api-keys-section";
import { ConnectorAccessSection } from "../_components/connector-access-section";
import { ConnectorsTab } from "../_components/connectors-tab";
+import { IngestPreviewSettingsSection } from "../_components/ingest-preview-settings-section";
import { IngestSettingsSection } from "../_components/ingest-settings-section";
import { LangflowUpdatesBanner } from "../_components/langflow-updates-banner";
import ModelProviders from "../_components/model-providers";
@@ -21,6 +22,7 @@ const VALID_TABS = [
"langflow",
"api-keys",
"connector-access",
+ "ingest-preview",
] as const;
type Tab = (typeof VALID_TABS)[number];
@@ -151,6 +153,7 @@ export default async function SettingsTabPage({
)}
{tab === "api-keys" && <ApiKeysSection />}
{tab === "connector-access" && <ConnectorAccessSection />}
+ {tab === "ingest-preview" && <IngestPreviewSettingsSection />}
</HydrationBoundary>
);
}
diff --git a/frontend/app/settings/_components/ingest-preview-settings-section.tsx b/frontend/app/settings/_components/ingest-preview-settings-section.tsx
new file mode 100644
index 000000000..1763f504e
--- /dev/null
+++ b/frontend/app/settings/_components/ingest-preview-settings-section.tsx
@@ -0,0 +1,188 @@
+"use client";
+
+import { useState } from "react";
+import { toast } from "sonner";
+import { IngestPreviewAutoOpenControl } from "@/components/ingest-preview-auto-open-control";
+import { IngestReviewDialog } from "@/components/ingest-review";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import {
+ INGEST_PREVIEW_AUTO_OPEN_OPTIONS,
+ type IngestPreviewSettings,
+ useIngestPreviewSettings,
+} from "@/hooks/use-ingest-preview-settings";
+import { createSampleDemoFile } from "@/lib/ingest-preview-demo";
+import { cn } from "@/lib/utils";
+
+const INGEST_PREVIEW_SETTING_KEYS = [
+ "autoOpen",
+ "showChunkBoundaries",
+ "showIndexingPipeline",
+ "showChunkContents",
+ "completionNotification",
+] as const satisfies ReadonlyArray<keyof IngestPreviewSettings>;
+
+function settingsEqual(
+ a: IngestPreviewSettings,
+ b: IngestPreviewSettings,
+): boolean {
+ return INGEST_PREVIEW_SETTING_KEYS.every((key) => a[key] === b[key]);
+}
+
+export function IngestPreviewSettingsSection() {
+ const { settings, updateSettings } = useIngestPreviewSettings();
+ const [draft, setDraft] = useState<IngestPreviewSettings>(settings);
+ const [prevSettings, setPrevSettings] = useState(settings);
+ const [showPreviewDialog, setShowPreviewDialog] = useState(false);
+ const [previewFile, setPreviewFile] = useState<File | null>(null);
+
+ // Hook hydrates from localStorage after mount — keep the form in sync when
+ // persisted values change (including after Save). Adjust during render instead
+ // of an effect: https://react.dev/learn/you-might-not-need-an-effect
+ if (settings !== prevSettings) {
+ setPrevSettings(settings);
+ setDraft(settings);
+ }
+
+ const isDirty = !settingsEqual(draft, settings);
+ const autoOpenDescription =
+ INGEST_PREVIEW_AUTO_OPEN_OPTIONS.find(
+ (option) => option.value === draft.autoOpen,
+ )?.description ?? INGEST_PREVIEW_AUTO_OPEN_OPTIONS[0].description;
+
+ const patchDraft = (patch: Partial<IngestPreviewSettings>) => {
+ setDraft((prev) => ({ ...prev, ...patch }));
+ };
+
+ const saveChanges = () => {
+ updateSettings(draft);
+ toast.success("Ingest preview settings saved");
+ };
+
+ const runSampleIngest = () => {
+ setPreviewFile(createSampleDemoFile());
+ setShowPreviewDialog(true);
+ };
+
+ return (
+ <div className="space-y-0" data-testid="ingest-preview-settings">
+ <div className="flex items-center justify-between gap-4 py-4 border-b border-border">
+ <div className="flex-1 min-w-0">
+ <Label className="text-base font-medium">
+ Auto-open ingest preview
+ </Label>
+ <p className="text-sm text-muted-foreground mt-1">
+ {autoOpenDescription}
+ </p>
+ </div>
+ <IngestPreviewAutoOpenControl
+ value={draft.autoOpen}
+ onChange={(autoOpen) => patchDraft({ autoOpen })}
+ aria-label="Auto-open ingest preview"
+ />
+ </div>
+
+ <SettingToggle
+ id="show-chunk-boundaries"
+ label="Show chunk boundaries"
+ description="Show the indexed chunk list for each document."
+ checked={draft.showChunkBoundaries}
+ onCheckedChange={(checked) =>
+ patchDraft({ showChunkBoundaries: checked })
+ }
+ />
+ <SettingToggle
+ id="show-indexing-pipeline"
+ label="Show indexing pipeline"
+ description="Reading layout, creating chunks, embeddings, stored."
+ checked={draft.showIndexingPipeline}
+ onCheckedChange={(checked) =>
+ patchDraft({ showIndexingPipeline: checked })
+ }
+ />
+ <SettingToggle
+ id="show-chunk-contents"
+ label="Show chunk contents"
+ description="Stream each chunk's extracted text as it is created."
+ checked={draft.showChunkContents}
+ onCheckedChange={(checked) =>
+ patchDraft({ showChunkContents: checked })
+ }
+ />
+ <SettingToggle
+ id="completion-notification"
+ label="Completion notification"
+ description="Show a 'Task completed' toast when ingestion finishes."
+ checked={draft.completionNotification}
+ onCheckedChange={(checked) =>
+ patchDraft({ completionNotification: checked })
+ }
+ last
+ />
+
+ <div className="flex flex-wrap items-center justify-end gap-2 pt-6">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={runSampleIngest}
+ data-testid="ingest-preview-run-sample"
+ >
+ <div>Run a sample ingest</div>
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ className="min-w-[120px]"
+ onClick={saveChanges}
+ disabled={!isDirty}
+ data-testid="ingest-preview-save"
+ >
+ Save changes
+ </Button>
+ </div>
+
+ <IngestReviewDialog
+ open={showPreviewDialog}
+ onOpenChange={setShowPreviewDialog}
+ demo
+ settingsOverride={draft}
+ previewFiles={previewFile ? [previewFile] : []}
+ />
+ </div>
+ );
+}
+
+function SettingToggle({
+ id,
+ label,
+ description,
+ checked,
+ onCheckedChange,
+ last = false,
+}: {
+ id: string;
+ label: string;
+ description: string;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ last?: boolean;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex items-center justify-between gap-4 py-4",
+ !last && "border-b border-border",
+ )}
+ >
+ <div className="flex-1 min-w-0">
+ <Label htmlFor={id} className="text-base font-medium">
+ {label}
+ </Label>
+ <p className="text-sm text-muted-foreground mt-1">{description}</p>
+ </div>
+ <Switch id={id} checked={checked} onCheckedChange={onCheckedChange} />
+ </div>
+ );
+}
diff --git a/frontend/app/settings/_components/settings-nav.tsx b/frontend/app/settings/_components/settings-nav.tsx
index 4a363c734..9395abcda 100644
--- a/frontend/app/settings/_components/settings-nav.tsx
+++ b/frontend/app/settings/_components/settings-nav.tsx
@@ -10,6 +10,7 @@ import {
canAccessConnectorAccessTab,
canShowRbacGatedSettingsTab,
} from "@/lib/brand";
+import { isIngestPreviewEnabled } from "@/lib/ingest-preview";
import { cn } from "@/lib/utils";
const TABS = [
@@ -23,6 +24,7 @@ const TABS = [
label: "Connector Settings",
perm: "connectors:manage:access",
},
+ { value: "ingest-preview", label: "Ingest preview", ingestPreviewTab: true },
] as const;
export function SettingsNav() {
@@ -34,6 +36,7 @@ export function SettingsNav() {
isIbmAuthMode,
isLoading,
permissionsResolved,
+ runMode,
} = useAuth();
const isCloudBrand = useIsCloudBrand();
const tabAccess = useSettingsTabAccess();
@@ -47,6 +50,8 @@ export function SettingsNav() {
if ("perm" in tab) return canShowRbacGatedSettingsTab(tab.perm, tabAccess);
if ("apiKeysTab" in tab)
return (isAuthenticated || isNoAuthMode) && !isIbmAuthMode;
+ if ("ingestPreviewTab" in tab)
+ return isIngestPreviewEnabled(runMode, { isCloudBrand });
return true;
});
diff --git a/frontend/components/docling-preview/index.ts b/frontend/components/docling-preview/index.ts
new file mode 100644
index 000000000..426600414
--- /dev/null
+++ b/frontend/components/docling-preview/index.ts
@@ -0,0 +1,2 @@
+export { DoclingParseViewer } from "./parse-viewer";
+export { DoclingTextPreview } from "./text-preview";
diff --git a/frontend/components/docling-preview/parse-viewer.tsx b/frontend/components/docling-preview/parse-viewer.tsx
new file mode 100644
index 000000000..4a01c93ba
--- /dev/null
+++ b/frontend/components/docling-preview/parse-viewer.tsx
@@ -0,0 +1,201 @@
+"use client";
+
+import {
+ type RefObject,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import type { DoclingImgElement, DoclingImgPageElement } from "./types";
+import { useChunkHighlightOverlay } from "./use-chunk-highlight-overlay";
+import {
+ CHUNK_HIT_STYLE,
+ itemOnDoclingPage,
+ itemSelfRef,
+ LAYOUT_BOX_STYLE,
+ loadDoclingComponents,
+ pageNoOf,
+} from "./utils";
+
+export function DoclingParseViewer({
+ doclingDocument,
+ highlightItemRefs,
+ fallbackPage,
+ chunkLabel,
+ scrollContainerRef,
+}: {
+ doclingDocument: Record<string, unknown>;
+ /** Matched Docling self_refs — styled in-place; all other annotations stay. */
+ highlightItemRefs?: string[];
+ /** When no item refs matched, emphasize every item on this 1-based Docling page. */
+ fallbackPage?: number | null;
+ /** e.g. "Chunk 5" — chip on the outer chunk border. */
+ chunkLabel?: string;
+ /** Preview frame with overflow — preferred scrollport for chunk jumps. */
+ scrollContainerRef?: RefObject<HTMLElement | null>;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const hostRef = useRef<HTMLDivElement>(null);
+ const viewerRef = useRef<DoclingImgElement | null>(null);
+ const matchedRefsRef = useRef<Set<string> | null>(null);
+ const fallbackPageRef = useRef<number | null>(null);
+ const [ready, setReady] = useState(false);
+ const [loadError, setLoadError] = useState(false);
+
+ matchedRefsRef.current = new Set(highlightItemRefs ?? []);
+ fallbackPageRef.current =
+ typeof fallbackPage === "number" ? fallbackPage : null;
+
+ const highlightKey = `${chunkLabel ?? ""}:${(highlightItemRefs ?? []).join(",")}:${fallbackPage ?? ""}`;
+ // Fingerprint content so React identity churn does not reassign `src`
+ // (re-rasterize resets scroll mid-selection).
+ const documentIdentity = useMemo(() => {
+ const pages = doclingDocument.pages;
+ const pageCount = Array.isArray(pages)
+ ? pages.length
+ : pages && typeof pages === "object"
+ ? Object.keys(pages).length
+ : 0;
+ const texts = Array.isArray(doclingDocument.texts)
+ ? doclingDocument.texts.length
+ : 0;
+ const tables = Array.isArray(doclingDocument.tables)
+ ? doclingDocument.tables.length
+ : 0;
+ return `${pageCount}:${texts}:${tables}`;
+ }, [doclingDocument]);
+ const documentIdentityRef = useRef<string>("");
+
+ const isChunkHit = useCallback((page: unknown, item: unknown): boolean => {
+ const refs = matchedRefsRef.current;
+ if (refs && refs.size > 0) {
+ const ref = itemSelfRef(item);
+ return Boolean(ref && refs.has(ref));
+ }
+ const pageNo = fallbackPageRef.current;
+ if (pageNo == null) return false;
+ const fromItem = itemOnDoclingPage(item, pageNo);
+ if (fromItem) return true;
+ // Some items lack prov — fall back to the rendered page's page_no.
+ return pageNoOf(page) === pageNo;
+ }, []);
+
+ const applyChunkStyles = useCallback(() => {
+ const viewer = viewerRef.current;
+ if (!viewer) return;
+ const partFn = (page: unknown, item: unknown) =>
+ isChunkHit(page, item) ? "chunk-hit" : "";
+ const styleFn = (page: unknown, item: unknown) =>
+ isChunkHit(page, item) ? CHUNK_HIT_STYLE : LAYOUT_BOX_STYLE;
+ viewer.itemPart = partFn;
+ viewer.itemStyle = styleFn;
+ viewer.requestUpdate?.();
+
+ const pages =
+ viewer.shadowRoot?.querySelectorAll<DoclingImgPageElement>(
+ "docling-img-page",
+ );
+ pages?.forEach((page) => {
+ page.itemPart = partFn;
+ page.itemStyle = styleFn;
+ page.requestUpdate?.();
+ });
+ }, [isChunkHit]);
+
+ const overlay = useChunkHighlightOverlay({
+ ready,
+ hostRef,
+ viewerRef,
+ scrollContainerRef,
+ chunkLabel,
+ highlightKey,
+ fallbackPage,
+ applyStyles: applyChunkStyles,
+ });
+
+ useEffect(() => {
+ let cancelled = false;
+ void loadDoclingComponents()
+ .then(() => {
+ if (cancelled) return;
+ setLoadError(false);
+ setReady(true);
+ })
+ .catch(() => {
+ if (cancelled) return;
+ setReady(false);
+ setLoadError(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ // Assigning `src` re-rasterizes embedded page images — only when the document
+ // identity changes. Chunk emphasis goes through itemPart/itemStyle.
+ useEffect(() => {
+ if (!ready || !containerRef.current) {
+ return;
+ }
+
+ const container = containerRef.current;
+ if (!viewerRef.current || !container.contains(viewerRef.current)) {
+ container.replaceChildren();
+ const viewer = document.createElement("docling-img") as DoclingImgElement;
+ viewer.setAttribute("pagenumbers", "");
+ viewer.trim = "";
+ container.appendChild(viewer);
+ viewerRef.current = viewer;
+ documentIdentityRef.current = "";
+ }
+
+ const viewer = viewerRef.current;
+ // Never filter via `items` — that hides other layout annotations.
+ viewer.items = undefined;
+ viewer.removeAttribute("items");
+ applyChunkStyles();
+ if (documentIdentityRef.current !== documentIdentity) {
+ documentIdentityRef.current = documentIdentity;
+ viewer.src = doclingDocument;
+ }
+ }, [ready, doclingDocument, documentIdentity, applyChunkStyles]);
+
+ if (loadError) {
+ return (
+ <div
+ className="flex h-40 items-center justify-center px-4 text-center text-xs text-muted-foreground"
+ data-testid="docling-parse-viewer-error"
+ >
+ Document preview failed to load. Try again in a moment.
+ </div>
+ );
+ }
+
+ return (
+ <div ref={hostRef} className="relative" data-testid="docling-parse-viewer">
+ {/* Imperative docling-img mount point — keep empty of React children. */}
+ <div ref={containerRef} />
+ {overlay && chunkLabel ? (
+ <div
+ className="pointer-events-none absolute z-10 rounded-md border-2 border-dashed border-blue-700 dark:border-blue-400"
+ style={{
+ top: overlay.top,
+ left: overlay.left,
+ width: overlay.width,
+ height: overlay.height,
+ }}
+ data-testid="docling-chunk-overlay"
+ >
+ <span
+ className="absolute -top-2.5 left-2 rounded px-1.5 py-0.5 text-xxs font-medium uppercase leading-none tracking-wide bg-blue-700 text-white dark:bg-blue-400"
+ data-testid="docling-chunk-label"
+ >
+ {chunkLabel}
+ </span>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/frontend/components/docling-preview/text-preview.tsx b/frontend/components/docling-preview/text-preview.tsx
new file mode 100644
index 000000000..837ef7aa2
--- /dev/null
+++ b/frontend/components/docling-preview/text-preview.tsx
@@ -0,0 +1,221 @@
+"use client";
+
+import Image from "next/image";
+import { type ReactNode, useLayoutEffect, useMemo, useRef } from "react";
+import type {
+ DoclingPictureItem,
+ DoclingTableItem,
+ DoclingTextItem,
+ ParsedItem,
+} from "./types";
+import {
+ collectParsedItems,
+ groupPreviewItems,
+ itemMatchesHighlight,
+ LABEL_NAMES,
+ MAX_TEXT_PREVIEW_ITEMS,
+ scrollNodeIntoPane,
+} from "./utils";
+
+function ParsedBlock({
+ label,
+ children,
+}: {
+ label: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="relative rounded-md border-2 border-dashed border-blue-600/70 bg-blue-600/[0.12] px-3 pt-4 pb-2 dark:border-blue-500 dark:bg-blue-500/15">
+ <span className="absolute -top-2 left-2 rounded px-1 py-px text-xxs font-medium uppercase leading-none tracking-wide bg-blue-600 text-white dark:bg-blue-500">
+ {label}
+ </span>
+ {children}
+ </div>
+ );
+}
+
+function DoclingTextLine({ item }: { item: DoclingTextItem }) {
+ const text = item.text?.trim();
+ if (!text) {
+ return null;
+ }
+ const label = item.label ?? "text";
+ const textClass =
+ label === "title"
+ ? "text-sm font-bold text-foreground"
+ : label === "section_header"
+ ? "text-sm font-semibold text-foreground"
+ : label === "list_item"
+ ? "pl-2 text-xs text-foreground"
+ : "text-xs text-foreground";
+ return (
+ <ParsedBlock label={LABEL_NAMES[label] ?? "Text"}>
+ <p className={textClass}>{label === "list_item" ? `• ${text}` : text}</p>
+ </ParsedBlock>
+ );
+}
+
+function DoclingTableBlock({ table }: { table: DoclingTableItem }) {
+ const grid = table.data?.grid;
+ if (!Array.isArray(grid) || grid.length === 0) {
+ return null;
+ }
+ return (
+ <ParsedBlock label="Table">
+ <div className="overflow-x-auto">
+ <table className="w-full border-collapse text-xxs">
+ <tbody>
+ {grid.map((row, rowIndex) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: parsed grid is static
+ <tr key={rowIndex}>
+ {row.map((cell, cellIndex) => (
+ <td
+ // biome-ignore lint/suspicious/noArrayIndexKey: parsed grid is static
+ key={cellIndex}
+ className="border border-border/40 px-2 py-1 align-top text-foreground"
+ >
+ {cell?.text ?? ""}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </ParsedBlock>
+ );
+}
+
+function DoclingPictureBlock({ picture }: { picture: DoclingPictureItem }) {
+ const uri = picture.image?.uri;
+ if (!uri) {
+ return (
+ <ParsedBlock label="Figure">
+ <p className="text-xxs text-muted-foreground">
+ Figure detected (image not embedded).
+ </p>
+ </ParsedBlock>
+ );
+ }
+ return (
+ <ParsedBlock label="Figure">
+ <Image
+ src={uri}
+ alt="Parsed figure"
+ width={640}
+ height={360}
+ unoptimized
+ className="max-h-48 h-auto w-auto rounded border border-border/40 bg-background object-contain"
+ />
+ </ParsedBlock>
+ );
+}
+
+function renderParsedItem(item: ParsedItem) {
+ if (item.kind === "table") {
+ return <DoclingTableBlock key={item.id} table={item.node} />;
+ }
+ if (item.kind === "picture") {
+ return <DoclingPictureBlock key={item.id} picture={item.node} />;
+ }
+ return <DoclingTextLine key={item.id} item={item.node} />;
+}
+
+/**
+ * Renders the parsed structure for formats that have no page rasters (docx,
+ * pptx, xlsx, html, csv, md, …). Type annotations stay visible; a selected
+ * chunk adds an outer Chunk N frame around matched regions.
+ */
+export function DoclingTextPreview({
+ doclingDocument,
+ highlightItemRefs,
+ highlightText,
+ chunkLabel,
+}: {
+ doclingDocument: Record<string, unknown>;
+ highlightItemRefs?: string[];
+ highlightText?: string;
+ chunkLabel?: string;
+}) {
+ // Fetch one extra item so we can show a "more regions" hint without walking
+ // the entire Docling tree for huge office docs.
+ const items = useMemo(
+ () => collectParsedItems(doclingDocument, MAX_TEXT_PREVIEW_ITEMS + 1),
+ [doclingDocument],
+ );
+ const truncated = items.length > MAX_TEXT_PREVIEW_ITEMS;
+ const visible = useMemo(
+ () => (truncated ? items.slice(0, MAX_TEXT_PREVIEW_ITEMS) : items),
+ [items, truncated],
+ );
+
+ const groups = useMemo(() => {
+ if (!chunkLabel) {
+ return visible.map((item) => ({ kind: "plain" as const, item }));
+ }
+ return groupPreviewItems(visible, (item) =>
+ itemMatchesHighlight(item, highlightItemRefs, highlightText),
+ );
+ }, [visible, chunkLabel, highlightItemRefs, highlightText]);
+
+ const chunkFrameRef = useRef<HTMLDivElement | null>(null);
+ const highlightKey = `${chunkLabel ?? ""}:${(highlightItemRefs ?? []).join(",")}:${highlightText ?? ""}`;
+ const firstChunkKey = useMemo(() => {
+ const first = groups.find((group) => group.kind === "chunk");
+ return first?.kind === "chunk"
+ ? first.items.map((item) => item.id).join("|")
+ : null;
+ }, [groups]);
+
+ useLayoutEffect(() => {
+ if (!chunkLabel || !firstChunkKey) return;
+ // Re-run when highlight refs/text change under the same chunk label.
+ void highlightKey;
+ const raf = window.requestAnimationFrame(() => {
+ scrollNodeIntoPane(chunkFrameRef.current);
+ });
+ return () => window.cancelAnimationFrame(raf);
+ }, [highlightKey, chunkLabel, firstChunkKey]);
+
+ if (items.length === 0) {
+ return (
+ <div className="flex h-40 items-center justify-center px-4 text-center text-xxs text-muted-foreground">
+ Parsing finished, but no extractable text or tables were found in this
+ document.
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className="space-y-3 rounded-md border border-border/40 bg-white p-4 shadow-sm dark:bg-slate-900"
+ data-testid="docling-text-preview"
+ >
+ {groups.map((group) => {
+ if (group.kind === "plain") {
+ return renderParsedItem(group.item);
+ }
+ const key = group.items.map((item) => item.id).join("|");
+ return (
+ <div
+ key={key}
+ ref={key === firstChunkKey ? chunkFrameRef : undefined}
+ className="relative space-y-3 rounded-md border-2 border-dashed border-blue-700 bg-blue-700/[0.06] p-3 pt-5 dark:border-blue-400"
+ data-testid="docling-text-chunk-frame"
+ >
+ <span className="absolute -top-2.5 left-2 rounded px-1.5 py-0.5 text-xxs font-medium uppercase leading-none tracking-wide bg-blue-700 text-white dark:bg-blue-400">
+ {chunkLabel}
+ </span>
+ {group.items.map((item) => renderParsedItem(item))}
+ </div>
+ );
+ })}
+ {truncated && (
+ <p className="text-xxs text-muted-foreground">
+ Showing first {MAX_TEXT_PREVIEW_ITEMS} regions — more remain in the
+ document
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/components/docling-preview/types.ts b/frontend/components/docling-preview/types.ts
new file mode 100644
index 000000000..bb3528801
--- /dev/null
+++ b/frontend/components/docling-preview/types.ts
@@ -0,0 +1,56 @@
+/** Lit lifecycle bits exposed by @docling/docling-components elements. */
+export type LitUpdatable = {
+ updateComplete?: Promise<boolean>;
+ requestUpdate?: () => void;
+};
+
+export type DoclingImgElement = HTMLElement &
+ LitUpdatable & {
+ src?: Record<string, unknown> | string;
+ items?: string | unknown[];
+ trim?: string;
+ itemStyle?: (page: unknown, item: unknown) => string;
+ itemPart?: (page: unknown, item: unknown) => string;
+ };
+
+export type DoclingImgPageElement = HTMLElement &
+ LitUpdatable & {
+ page?: { page_no?: number };
+ itemStyle?: (page: unknown, item: unknown) => string;
+ itemPart?: (page: unknown, item: unknown) => string;
+ };
+
+export type OverlayBox = {
+ top: number;
+ left: number;
+ width: number;
+ height: number;
+};
+
+export type DoclingTextItem = {
+ text?: string;
+ label?: string;
+ level?: number;
+};
+
+export type DoclingTableCell = { text?: string };
+
+export type DoclingTableItem = {
+ data?: { grid?: DoclingTableCell[][] };
+};
+
+export type DoclingPictureItem = {
+ image?: { uri?: string };
+ captions?: unknown[];
+};
+
+export type DoclingRef = { $ref?: string; cref?: string };
+
+export type ParsedItem =
+ | { kind: "text"; id: string; node: DoclingTextItem }
+ | { kind: "table"; id: string; node: DoclingTableItem }
+ | { kind: "picture"; id: string; node: DoclingPictureItem };
+
+export type PreviewGroup =
+ | { kind: "chunk"; items: ParsedItem[] }
+ | { kind: "plain"; item: ParsedItem };
diff --git a/frontend/components/docling-preview/use-chunk-highlight-overlay.ts b/frontend/components/docling-preview/use-chunk-highlight-overlay.ts
new file mode 100644
index 000000000..1e588712a
--- /dev/null
+++ b/frontend/components/docling-preview/use-chunk-highlight-overlay.ts
@@ -0,0 +1,173 @@
+import { type RefObject, useLayoutEffect, useState } from "react";
+import type { DoclingImgElement, OverlayBox } from "./types";
+import {
+ collectChunkHitElements,
+ collectChunkHitRects,
+ collectPageItemElements,
+ findDoclingPageAnchor,
+ findDoclingPageElement,
+ findScrollParent,
+ hitRectsSignature,
+ LIT_UPDATE_TIMEOUT_MS,
+ scrollElementThroughAncestors,
+ unionRect,
+ waitForDoclingLitPaint,
+} from "./utils";
+
+/**
+ * Applies chunk hit styles, scrolls to the chunk's page, then places the
+ * Chunk N overlay once geometry is fresh.
+ *
+ * Important: clear the previous overlay immediately — otherwise `chunkLabel`
+ * updates (Chunk 1 → 19) while the old box stays put during the Lit wait.
+ */
+export function useChunkHighlightOverlay({
+ ready,
+ hostRef,
+ viewerRef,
+ scrollContainerRef,
+ chunkLabel,
+ highlightKey,
+ fallbackPage,
+ applyStyles,
+}: {
+ ready: boolean;
+ hostRef: RefObject<HTMLDivElement | null>;
+ viewerRef: RefObject<DoclingImgElement | null>;
+ scrollContainerRef?: RefObject<HTMLElement | null>;
+ chunkLabel?: string;
+ highlightKey: string;
+ fallbackPage?: number | null;
+ applyStyles: () => void;
+}) {
+ const [overlay, setOverlay] = useState<OverlayBox | null>(null);
+
+ useLayoutEffect(() => {
+ if (!ready || !chunkLabel) {
+ setOverlay(null);
+ return;
+ }
+ // Selection fingerprint (label + item refs + page) — read so the effect
+ // re-runs when only refs/page change under the same chunk label.
+ void highlightKey;
+
+ const host = hostRef.current;
+ const viewer = viewerRef.current;
+ // Drop stale "Chunk N" chrome before the new geometry is ready.
+ setOverlay(null);
+ if (!host || !viewer) return;
+
+ const beforeSignature = hitRectsSignature(collectChunkHitRects(viewer));
+ applyStyles();
+
+ let cancelled = false;
+ let timeoutId: number | undefined;
+
+ const resolvePageNo = (): number | null => {
+ if (typeof fallbackPage !== "number") return null;
+ for (const pageNo of [fallbackPage, fallbackPage + 1, fallbackPage - 1]) {
+ if (pageNo < 1) continue;
+ if (findDoclingPageElement(viewer, pageNo)) return pageNo;
+ }
+ return fallbackPage;
+ };
+
+ const preferredScrollContainers = () => [
+ scrollContainerRef?.current,
+ findScrollParent(host),
+ ];
+
+ const scrollToAnchor = (anchor: Element | null) => {
+ if (!anchor) return;
+ scrollElementThroughAncestors(anchor, preferredScrollContainers());
+ };
+
+ const placeOverlay = (hitEls: Element[]) => {
+ if (cancelled || hitEls.length === 0) {
+ if (!cancelled) setOverlay(null);
+ return;
+ }
+ const hitRects = hitEls.map((el) => el.getBoundingClientRect());
+ const hostRect = host.getBoundingClientRect();
+ setOverlay(
+ unionRect(hitRects, hostRect, host.scrollTop, host.scrollLeft),
+ );
+ };
+
+ const pageNo = resolvePageNo();
+ const pageAnchor =
+ pageNo != null ? findDoclingPageAnchor(viewer, pageNo) : null;
+
+ const finish = (hitEls: Element[], refineScroll: boolean) => {
+ if (cancelled) return;
+ // Overlay is host-relative so it stays correct during the smooth scroll.
+ placeOverlay(hitEls);
+ // Single smooth scroll only — a second scrollTo cancels the animation.
+ const anchor =
+ refineScroll && hitEls[0] ? hitEls[0] : (pageAnchor ?? hitEls[0]);
+ scrollToAnchor(anchor ?? null);
+ };
+
+ const pageItemElements = (): SVGRectElement[] => {
+ if (pageNo == null) return [];
+ return collectPageItemElements(viewer, pageNo);
+ };
+
+ const placeFromGeometry = () => {
+ if (cancelled) return;
+
+ const hitEls = collectChunkHitElements(viewer);
+ const signature = hitRectsSignature(
+ hitEls.map((el) => el.getBoundingClientRect()),
+ );
+ const hitsAreFresh =
+ hitEls.length > 0 &&
+ (beforeSignature === "" || signature !== beforeSignature);
+
+ if (hitsAreFresh) {
+ finish(hitEls, true);
+ return;
+ }
+
+ // Fall back to page geometry so the Chunk N frame still appears.
+ const pageEls = pageItemElements();
+ if (pageEls.length > 0) {
+ finish(pageEls, false);
+ return;
+ }
+ if (pageAnchor) {
+ finish([pageAnchor], false);
+ }
+ };
+
+ const timeout = new Promise<void>((resolve) => {
+ timeoutId = window.setTimeout(resolve, LIT_UPDATE_TIMEOUT_MS);
+ });
+
+ void Promise.race([waitForDoclingLitPaint(viewer), timeout]).then(() => {
+ if (timeoutId !== undefined) {
+ window.clearTimeout(timeoutId);
+ timeoutId = undefined;
+ }
+ placeFromGeometry();
+ });
+
+ return () => {
+ cancelled = true;
+ if (timeoutId !== undefined) {
+ window.clearTimeout(timeoutId);
+ }
+ };
+ }, [
+ ready,
+ chunkLabel,
+ highlightKey,
+ fallbackPage,
+ applyStyles,
+ hostRef,
+ viewerRef,
+ scrollContainerRef,
+ ]);
+
+ return overlay;
+}
diff --git a/frontend/components/docling-preview/utils.ts b/frontend/components/docling-preview/utils.ts
new file mode 100644
index 000000000..1a7e3e357
--- /dev/null
+++ b/frontend/components/docling-preview/utils.ts
@@ -0,0 +1,481 @@
+import type {
+ DoclingImgElement,
+ DoclingImgPageElement,
+ DoclingPictureItem,
+ DoclingRef,
+ DoclingTableItem,
+ DoclingTextItem,
+ LitUpdatable,
+ OverlayBox,
+ ParsedItem,
+ PreviewGroup,
+} from "./types";
+
+/**
+ * Hard deadline so a hung Lit update cannot stall chunk overlay placement.
+ * Not a poll interval — raced once against updateComplete + one rAF.
+ */
+export const LIT_UPDATE_TIMEOUT_MS = 1000;
+
+export const LAYOUT_BOX_STYLE =
+ "stroke: rgb(37, 99, 235); stroke-width: 2px; fill: rgba(37, 99, 235, 0.12); fill-opacity: 1;";
+
+/** Stronger dashed stroke for items that belong to the selected chunk. */
+export const CHUNK_HIT_STYLE =
+ "stroke: rgb(29, 78, 216); stroke-width: 3px; stroke-dasharray: 6 3; fill: rgba(37, 99, 235, 0.18); fill-opacity: 1;";
+
+export const LABEL_NAMES: Record<string, string> = {
+ title: "Title",
+ section_header: "Heading",
+ list_item: "List",
+ caption: "Caption",
+ page_header: "Header",
+ page_footer: "Footer",
+ footnote: "Footnote",
+};
+
+/** Cap DOM nodes for huge office docs (full set stays in the index on the right). */
+export const MAX_TEXT_PREVIEW_ITEMS = 120;
+
+let doclingComponentsLoaded: Promise<void> | null = null;
+
+export function loadDoclingComponents(): Promise<void> {
+ if (typeof window === "undefined") {
+ return Promise.resolve();
+ }
+ if (!doclingComponentsLoaded) {
+ doclingComponentsLoaded = import("@docling/docling-components")
+ .then(() => undefined)
+ .catch((error) => {
+ // Clear so a later mount can retry the dynamic import.
+ doclingComponentsLoaded = null;
+ throw error;
+ });
+ }
+ return doclingComponentsLoaded;
+}
+
+export function itemSelfRef(item: unknown): string | undefined {
+ if (!item || typeof item !== "object") return undefined;
+ const ref = (item as { self_ref?: unknown }).self_ref;
+ return typeof ref === "string" ? ref : undefined;
+}
+
+export function itemOnDoclingPage(item: unknown, pageNo: number): boolean {
+ if (!item || typeof item !== "object") return false;
+ const prov = (item as { prov?: Array<{ page_no?: number }> }).prov;
+ if (!Array.isArray(prov) || prov.length === 0) return false;
+ return prov.some((p) => p.page_no === pageNo);
+}
+
+export function pageNoOf(page: unknown): number | null {
+ if (!page || typeof page !== "object") return null;
+ const n = (page as { page_no?: unknown }).page_no;
+ return typeof n === "number" ? n : null;
+}
+
+function isScrollableOverflowY(el: HTMLElement): boolean {
+ const { overflowY } = getComputedStyle(el);
+ return (
+ overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay"
+ );
+}
+
+export function findScrollParent(el: HTMLElement): HTMLElement | null {
+ let node: HTMLElement | null = el.parentElement;
+ let overflowCandidate: HTMLElement | null = null;
+ while (node) {
+ if (isScrollableOverflowY(node)) {
+ // Prefer an ancestor that can actually scroll. Nested overflow-auto
+ // frames (preview pane inside a dialog) often have no overflow while the
+ // outer dialog does — scrolling the inner one is a silent no-op.
+ if (node.scrollHeight > node.clientHeight + 1) {
+ return node;
+ }
+ overflowCandidate ??= node;
+ }
+ node = node.parentElement;
+ }
+ return overflowCandidate;
+}
+
+function targetScrollTop(
+ el: Element,
+ scrollParent: HTMLElement,
+ paddingPx: number,
+): number | null {
+ const parentRect = scrollParent.getBoundingClientRect();
+ const elRect = el.getBoundingClientRect();
+ if (elRect.width === 0 && elRect.height === 0) return null;
+ return Math.max(
+ 0,
+ elRect.top - parentRect.top + scrollParent.scrollTop - paddingPx,
+ );
+}
+
+/**
+ * Smooth-scroll the primary overflow container to `el`. Only one container is
+ * animated — repeated scrollTo calls cancel the browser's smooth animation.
+ */
+export function scrollElementThroughAncestors(
+ el: Element,
+ preferredContainers: Array<HTMLElement | null | undefined>,
+ paddingPx = 48,
+) {
+ const seen = new Set<HTMLElement>();
+ const candidates: HTMLElement[] = [];
+ for (const preferred of preferredContainers) {
+ if (
+ preferred &&
+ preferred.scrollHeight > preferred.clientHeight + 1 &&
+ !seen.has(preferred)
+ ) {
+ seen.add(preferred);
+ candidates.push(preferred);
+ }
+ }
+
+ let current: Element | null = el;
+ while (current) {
+ const parentNode: Node | null = current.parentNode;
+ if (!parentNode) break;
+ if (parentNode instanceof ShadowRoot) {
+ current = parentNode.host;
+ continue;
+ }
+ if (!(parentNode instanceof HTMLElement)) break;
+ if (
+ isScrollableOverflowY(parentNode) &&
+ parentNode.scrollHeight > parentNode.clientHeight + 1 &&
+ !seen.has(parentNode)
+ ) {
+ seen.add(parentNode);
+ candidates.push(parentNode);
+ }
+ current = parentNode;
+ }
+
+ const primary = candidates[0];
+ if (!primary) return;
+ const top = targetScrollTop(el, primary, paddingPx);
+ if (top == null) return;
+ primary.scrollTo({ top, behavior: "smooth" });
+}
+
+export function listDoclingPageElements(
+ viewer: DoclingImgElement,
+): DoclingImgPageElement[] {
+ const root = viewer.shadowRoot;
+ if (!root) return [];
+ return Array.from(
+ root.querySelectorAll<DoclingImgPageElement>("docling-img-page"),
+ );
+}
+
+export function findDoclingPageElement(
+ viewer: DoclingImgElement,
+ pageNo: number,
+): DoclingImgPageElement | null {
+ const pages = listDoclingPageElements(viewer);
+ for (const pageEl of pages) {
+ if (pageEl.page?.page_no === pageNo) return pageEl;
+ }
+ // Index fallback when Lit hasn't hydrated `.page` yet (1-based).
+ return pages[pageNo - 1] ?? null;
+}
+
+function awaitLitUpdate(node: LitUpdatable): Promise<void> {
+ return Promise.resolve(node.updateComplete).then(() => undefined);
+}
+
+function nextAnimationFrame(): Promise<void> {
+ return new Promise((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+}
+
+/**
+ * Wait for the viewer and nested page Lit elements to finish updating, then
+ * one animation frame so getBoundingClientRect reflects laid-out geometry.
+ * Parent updateComplete does not wait for children by default.
+ */
+export async function waitForDoclingLitPaint(
+ viewer: DoclingImgElement,
+): Promise<void> {
+ const pages = listDoclingPageElements(viewer);
+ await Promise.all([
+ awaitLitUpdate(viewer),
+ ...pages.map((page) => awaitLitUpdate(page)),
+ ]);
+ await nextAnimationFrame();
+}
+
+/**
+ * `docling-img-page` hosts have no :host display rule (default inline) and can
+ * report a 0×0 box. Scroll/measure the inner `.page` / SVG instead.
+ */
+export function findDoclingPageAnchor(
+ viewer: DoclingImgElement,
+ pageNo: number,
+): Element | null {
+ const pageEl = findDoclingPageElement(viewer, pageNo);
+ if (!pageEl) return null;
+ const inner =
+ pageEl.shadowRoot?.querySelector(".page") ??
+ pageEl.shadowRoot?.querySelector("svg.base") ??
+ pageEl.shadowRoot?.querySelector("svg") ??
+ null;
+ return inner ?? pageEl;
+}
+
+export function unionRect(
+ rects: DOMRect[],
+ hostRect: DOMRect,
+ scrollTop: number,
+ scrollLeft: number,
+): OverlayBox | null {
+ if (rects.length === 0) return null;
+ let top = Number.POSITIVE_INFINITY;
+ let left = Number.POSITIVE_INFINITY;
+ let bottom = Number.NEGATIVE_INFINITY;
+ let right = Number.NEGATIVE_INFINITY;
+ for (const r of rects) {
+ top = Math.min(top, r.top);
+ left = Math.min(left, r.left);
+ bottom = Math.max(bottom, r.bottom);
+ right = Math.max(right, r.right);
+ }
+ return {
+ top: top - hostRect.top + scrollTop,
+ left: left - hostRect.left + scrollLeft,
+ width: right - left,
+ height: bottom - top,
+ };
+}
+
+export function collectChunkHitElements(
+ viewer: DoclingImgElement,
+): SVGRectElement[] {
+ const root = viewer.shadowRoot;
+ if (!root) return [];
+
+ const elements: SVGRectElement[] = [];
+ // docling-img-page is a nested Lit element with its own shadow root; rects
+ // live there, not on the parent docling-img shadow tree.
+ const pages = listDoclingPageElements(viewer);
+ if (pages.length > 0) {
+ for (const page of pages) {
+ const pageRoot = page.shadowRoot;
+ if (!pageRoot) continue;
+ for (const rect of pageRoot.querySelectorAll<SVGRectElement>(
+ "rect[part~='chunk-hit']",
+ )) {
+ elements.push(rect);
+ }
+ }
+ return elements;
+ }
+
+ for (const rect of root.querySelectorAll<SVGRectElement>(
+ "rect[part~='chunk-hit']",
+ )) {
+ elements.push(rect);
+ }
+ return elements;
+}
+
+export function collectChunkHitRects(viewer: DoclingImgElement): DOMRect[] {
+ return collectChunkHitElements(viewer).map((el) =>
+ el.getBoundingClientRect(),
+ );
+}
+
+/** Stable geometry fingerprint so we can detect when Lit cleared stale hits. */
+export function hitRectsSignature(rects: DOMRect[]): string {
+ if (rects.length === 0) return "";
+ return rects
+ .map(
+ (r) =>
+ `${Math.round(r.top)}:${Math.round(r.left)}:${Math.round(r.width)}:${Math.round(r.height)}`,
+ )
+ .join("|");
+}
+
+export function collectPageItemElements(
+ viewer: DoclingImgElement,
+ pageNo: number,
+): SVGRectElement[] {
+ const elements: SVGRectElement[] = [];
+ for (const pageEl of listDoclingPageElements(viewer)) {
+ const pageRoot = pageEl.shadowRoot;
+ if (!pageRoot || pageEl.page?.page_no !== pageNo) continue;
+ for (const rect of pageRoot.querySelectorAll<SVGRectElement>(
+ "rect[part~='item']",
+ )) {
+ elements.push(rect);
+ }
+ }
+ return elements;
+}
+
+function refPath(ref: DoclingRef | undefined): string | undefined {
+ return ref?.$ref ?? ref?.cref;
+}
+
+function resolveRef(
+ document: Record<string, unknown>,
+ path: string,
+): Record<string, unknown> | null {
+ if (!path.startsWith("#/")) {
+ return null;
+ }
+ let node: unknown = document;
+ for (const part of path.slice(2).split("/")) {
+ if (node == null) {
+ return null;
+ }
+ node = Array.isArray(node)
+ ? node[Number(part)]
+ : (node as Record<string, unknown>)[part];
+ }
+ return (node as Record<string, unknown>) ?? null;
+}
+
+/**
+ * Walks the DoclingDocument body in reading order, resolving refs to texts,
+ * tables, and pictures. Recurses through groups and through children nested
+ * under text/table/picture nodes (common for HTML, where Docling nests body
+ * content under title/section_header parents). Falls back to concatenating
+ * the top-level arrays when no body ordering is present.
+ * Stops once `limit` items are collected (used to cap the left-pane DOM).
+ */
+export function collectParsedItems(
+ document: Record<string, unknown>,
+ limit: number,
+): ParsedItem[] {
+ const result: ParsedItem[] = [];
+ const seen = new Set<string>();
+
+ const walk = (children: unknown): void => {
+ if (!Array.isArray(children) || result.length >= limit) {
+ return;
+ }
+ for (const ref of children) {
+ if (result.length >= limit) return;
+ const path = refPath(ref as DoclingRef);
+ if (!path || seen.has(path)) {
+ continue;
+ }
+ seen.add(path);
+ const node = resolveRef(document, path);
+ if (!node) {
+ continue;
+ }
+ if (path.startsWith("#/texts")) {
+ result.push({ kind: "text", id: path, node });
+ // HTML Docling trees nest following content under heading nodes.
+ walk(node.children);
+ } else if (path.startsWith("#/tables")) {
+ result.push({ kind: "table", id: path, node });
+ walk(node.children);
+ } else if (path.startsWith("#/pictures")) {
+ result.push({ kind: "picture", id: path, node });
+ walk(node.children);
+ } else if (path.startsWith("#/groups")) {
+ walk(node.children);
+ }
+ }
+ };
+
+ const body = document.body as { children?: unknown } | undefined;
+ walk(body?.children);
+
+ if (result.length === 0) {
+ const texts = (document.texts as DoclingTextItem[] | undefined) ?? [];
+ for (let i = 0; i < texts.length; i += 1) {
+ if (result.length >= limit) break;
+ result.push({ kind: "text", id: `#/texts/${i}`, node: texts[i] });
+ }
+ const tables = (document.tables as DoclingTableItem[] | undefined) ?? [];
+ for (let i = 0; i < tables.length; i += 1) {
+ if (result.length >= limit) break;
+ result.push({ kind: "table", id: `#/tables/${i}`, node: tables[i] });
+ }
+ const pictures =
+ (document.pictures as DoclingPictureItem[] | undefined) ?? [];
+ for (let i = 0; i < pictures.length; i += 1) {
+ if (result.length >= limit) break;
+ result.push({
+ kind: "picture",
+ id: `#/pictures/${i}`,
+ node: pictures[i],
+ });
+ }
+ }
+ return result;
+}
+
+function normalizeNeedle(value: string): string {
+ return value.toLowerCase().replace(/\s+/g, " ").trim();
+}
+
+function parsedItemText(item: ParsedItem): string {
+ if (item.kind === "text") return item.node.text ?? "";
+ if (item.kind === "table") {
+ const grid = item.node.data?.grid;
+ if (!Array.isArray(grid)) return "";
+ return grid.flatMap((row) => row.map((cell) => cell?.text ?? "")).join(" ");
+ }
+ return "";
+}
+
+export function itemMatchesHighlight(
+ item: ParsedItem,
+ highlightItemRefs: string[] | undefined,
+ highlightText: string | undefined,
+): boolean {
+ // Refs win exclusively — also applying text OR creates a second "Chunk N"
+ // frame on non-consecutive regions that share phrases.
+ if (highlightItemRefs && highlightItemRefs.length > 0) {
+ return highlightItemRefs.includes(item.id);
+ }
+ if (!highlightText?.trim()) return false;
+ const needle = normalizeNeedle(highlightText);
+ const hay = normalizeNeedle(parsedItemText(item));
+ if (!hay) return false;
+ return hay.includes(needle) || needle.includes(hay);
+}
+
+/** Collapse consecutive matched items into one outer Chunk N frame. */
+export function groupPreviewItems(
+ items: ParsedItem[],
+ isHit: (item: ParsedItem) => boolean,
+): PreviewGroup[] {
+ const groups: PreviewGroup[] = [];
+ for (const item of items) {
+ if (isHit(item)) {
+ const last = groups[groups.length - 1];
+ if (last?.kind === "chunk") {
+ last.items.push(item);
+ } else {
+ groups.push({ kind: "chunk", items: [item] });
+ }
+ } else {
+ groups.push({ kind: "plain", item });
+ }
+ }
+ return groups;
+}
+
+export function scrollNodeIntoPane(node: HTMLElement | null) {
+ if (!node) return;
+ const scrollParent = findScrollParent(node);
+ if (!scrollParent) {
+ node.scrollIntoView({ block: "nearest", behavior: "smooth" });
+ return;
+ }
+ const parentRect = scrollParent.getBoundingClientRect();
+ const nodeRect = node.getBoundingClientRect();
+ const top = nodeRect.top - parentRect.top + scrollParent.scrollTop - 24;
+ scrollParent.scrollTo({ top: Math.max(0, top), behavior: "smooth" });
+}
diff --git a/frontend/components/file-chunks-panel.tsx b/frontend/components/file-chunks-panel.tsx
new file mode 100644
index 000000000..35ee119b7
--- /dev/null
+++ b/frontend/components/file-chunks-panel.tsx
@@ -0,0 +1,297 @@
+"use client";
+
+import { Check, Copy, Loader2 } from "lucide-react";
+import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";
+import { useFileScopedChunksQuery } from "@/app/api/queries/useFileScopedChunksQuery";
+import type { ChunkResult } from "@/app/api/queries/useGetSearchQuery";
+import { KnowledgeSearchInput } from "@/components/knowledge-search-input";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { trackButton } from "@/lib/analytics";
+import { cn } from "@/lib/utils";
+
+/** Document order for stable Chunk N labels (search hit order is not page order). */
+function compareChunksByDocumentOrder(a: ChunkResult, b: ChunkResult): number {
+ const pageA = typeof a.page === "number" ? a.page : Number.POSITIVE_INFINITY;
+ const pageB = typeof b.page === "number" ? b.page : Number.POSITIVE_INFINITY;
+ if (pageA !== pageB) return pageA - pageB;
+ return (a.chunk_id ?? a.id ?? "").localeCompare(b.chunk_id ?? b.id ?? "");
+}
+
+export interface FileChunksPanelProps {
+ filename: string;
+ /** Compact layout for dialogs (e.g. ingest review). */
+ compact?: boolean;
+ /** When false, show metadata only (no chunk body). Default true. */
+ showContents?: boolean;
+ selectedPage?: number | null;
+ /** Prefer exact chunk selection over page-wide selection. */
+ selectedChunkIndex?: number | null;
+ onChunkSelect?: (chunk: ChunkResult) => void;
+ className?: string;
+ /** Hide built-in search (parent renders it elsewhere, e.g. above pipeline steps). */
+ hideSearch?: boolean;
+ /** Controlled filter query — use with hideSearch when search lives outside the panel. */
+ filterQuery?: string;
+ onFilterQueryChange?: (query: string) => void;
+ /** Grow to fill parent height (ingest-review expand); replaces compact max-height. */
+ fillHeight?: boolean;
+}
+
+function chunkMatches(chunk: ChunkResult, needle: string): boolean {
+ return (
+ chunk.text.toLowerCase().includes(needle) ||
+ (chunk.index != null && String(chunk.index).includes(needle))
+ );
+}
+
+function FileChunkCard({
+ chunk,
+ listIndex,
+ compact,
+ showContents,
+ selected,
+ interactive,
+ copied,
+ onCopy,
+ onSelect,
+}: {
+ chunk: ChunkResult;
+ listIndex: number;
+ compact: boolean;
+ showContents: boolean;
+ selected: boolean;
+ interactive: boolean;
+ copied: boolean;
+ onCopy: (text: string, listIndex: number) => void;
+ onSelect?: () => void;
+}) {
+ const cardClass = cn(
+ "min-w-0 rounded-lg border border-border/50 bg-muted p-3 text-left",
+ compact && "p-2.5",
+ interactive && "w-full transition-colors hover:border-primary/40",
+ selected && "border-primary/60 ring-1 ring-primary/30",
+ );
+
+ const body = (
+ <>
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span className={cn("font-bold", compact ? "text-xs" : "text-sm")}>
+ Chunk {chunk.index}
+ </span>
+ <Badge variant="secondary" className="text-xxs">
+ {chunk.text.length} chars
+ </Badge>
+ {!compact && (
+ <Button
+ onClick={(e) => {
+ e.stopPropagation();
+ onCopy(chunk.text, listIndex);
+ }}
+ variant="ghost"
+ size="sm"
+ type="button"
+ aria-label={copied ? "Chunk copied" : "Copy chunk text"}
+ >
+ {copied ? (
+ <Check className="text-muted-foreground" />
+ ) : (
+ <Copy className="text-muted-foreground" />
+ )}
+ </Button>
+ )}
+ </div>
+ {typeof chunk.score === "number" && chunk.score > 0 && (
+ <Badge variant="secondary" className="shrink-0 text-xxs">
+ {chunk.score.toFixed(2)} score
+ </Badge>
+ )}
+ </div>
+ {showContents ? (
+ <blockquote
+ className={cn(
+ "min-w-0 text-muted-foreground leading-relaxed break-words [overflow-wrap:anywhere] whitespace-pre-wrap",
+ compact ? "text-xs" : "text-sm ml-1.5",
+ )}
+ >
+ {chunk.text}
+ </blockquote>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ {chunk.page != null ? `page ${chunk.page}` : "chunk"} ·{" "}
+ {chunk.text.length} chars
+ </p>
+ )}
+ </>
+ );
+
+ if (interactive) {
+ return (
+ <button type="button" className={cardClass} onClick={onSelect}>
+ {body}
+ </button>
+ );
+ }
+
+ return <div className={cardClass}>{body}</div>;
+}
+
+/**
+ * Searchable per-file chunk list shared by `/knowledge/chunks` and ingest review.
+ * Loads this file’s chunks once, then filters locally so paste-from-chunk works.
+ */
+export function FileChunksPanel({
+ filename,
+ compact = false,
+ showContents = true,
+ selectedPage,
+ selectedChunkIndex,
+ onChunkSelect,
+ className,
+ hideSearch = false,
+ filterQuery,
+ onFilterQueryChange,
+ fillHeight = false,
+}: FileChunksPanelProps) {
+ const { file, isFetching } = useFileScopedChunksQuery(filename);
+ const allChunks = useMemo(() => {
+ const sorted = [...(file?.chunks ?? [])].sort(compareChunksByDocumentOrder);
+ return sorted.map((chunk, i) => ({
+ ...chunk,
+ index: i + 1,
+ }));
+ }, [file?.chunks]);
+
+ const filterControlled = filterQuery !== undefined;
+ const [internalQuery, setInternalQuery] = useState("");
+ const [prevFilename, setPrevFilename] = useState(filename);
+ if (!filterControlled && filename !== prevFilename) {
+ setPrevFilename(filename);
+ setInternalQuery("");
+ }
+
+ const localQuery = filterControlled ? filterQuery : internalQuery;
+ const setLocalQuery = filterControlled
+ ? (query: string) => onFilterQueryChange?.(query)
+ : setInternalQuery;
+
+ const deferredQuery = useDeferredValue(localQuery);
+ const needle = deferredQuery.trim().toLowerCase();
+ const chunks = needle
+ ? allChunks.filter((chunk) => chunkMatches(chunk, needle))
+ : allChunks;
+
+ const [copiedIndex, setCopiedIndex] = useState<number | null>(null);
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(
+ () => () => {
+ if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
+ },
+ [],
+ );
+
+ const handleCopy = async (text: string, listIndex: number) => {
+ trackButton({
+ CTA: "Copy Chunk Text",
+ elementId: "copy-chunk-button",
+ namespace: "knowledge",
+ });
+ try {
+ await navigator.clipboard.writeText(text.trim());
+ } catch {
+ return;
+ }
+ setCopiedIndex(listIndex);
+ if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
+ copyTimerRef.current = setTimeout(() => setCopiedIndex(null), 10_000);
+ };
+
+ const emptyHeight = compact ? "h-40" : "h-64";
+
+ return (
+ <div
+ className={cn(
+ "flex min-h-0 flex-col gap-3",
+ fillHeight && "h-full",
+ className,
+ )}
+ data-testid="file-chunks-panel"
+ >
+ {!hideSearch && (
+ <KnowledgeSearchInput
+ value={localQuery}
+ onSearch={setLocalQuery}
+ onClear={() => setLocalQuery("")}
+ hideFilterChip
+ placeholder="Search chunks…"
+ />
+ )}
+
+ {isFetching ? (
+ <div
+ className={cn(
+ "flex items-center justify-center text-muted-foreground",
+ emptyHeight,
+ )}
+ >
+ <div className="text-center">
+ <Loader2 className="mx-auto mb-3 h-8 w-8 animate-spin opacity-50" />
+ <p className={cn(compact ? "text-sm" : "text-lg")}>
+ Loading chunks…
+ </p>
+ </div>
+ </div>
+ ) : chunks.length === 0 ? (
+ <div
+ className={cn(
+ "flex items-center justify-center text-muted-foreground",
+ emptyHeight,
+ )}
+ >
+ <div className="text-center">
+ <p className={cn("font-semibold", compact ? "text-sm" : "text-xl")}>
+ No knowledge
+ </p>
+ <p className="mt-1 text-sm text-secondary-foreground">
+ {needle
+ ? "No chunks match your search."
+ : "Chunks will appear here once the file is indexed."}
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div
+ className={cn(
+ "space-y-3 overflow-auto",
+ fillHeight ? "min-h-0 flex-1" : compact ? "max-h-72" : "pb-6",
+ )}
+ >
+ {chunks.map((chunk) => {
+ const chunkKey = chunk.index ?? 0;
+ const selected =
+ selectedChunkIndex != null
+ ? chunk.index === selectedChunkIndex
+ : selectedPage != null && chunk.page === selectedPage;
+ return (
+ <FileChunkCard
+ key={`${chunk.filename}-${chunkKey}`}
+ chunk={chunk}
+ listIndex={chunkKey}
+ compact={compact}
+ showContents={showContents}
+ selected={selected}
+ interactive={Boolean(onChunkSelect)}
+ copied={copiedIndex === chunkKey}
+ onCopy={handleCopy}
+ onSelect={
+ onChunkSelect ? () => onChunkSelect(chunk) : undefined
+ }
+ />
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/components/ingest-preview-auto-open-control.tsx b/frontend/components/ingest-preview-auto-open-control.tsx
new file mode 100644
index 000000000..0532e04a9
--- /dev/null
+++ b/frontend/components/ingest-preview-auto-open-control.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/settings-tabs";
+import { useIsCloudBrand } from "@/contexts/brand-context";
+import {
+ INGEST_PREVIEW_AUTO_OPEN_OPTIONS,
+ type IngestPreviewAutoOpen,
+} from "@/hooks/use-ingest-preview-settings";
+import { cn } from "@/lib/utils";
+
+export function IngestPreviewAutoOpenControl({
+ value,
+ onChange,
+ "aria-label": ariaLabel = "Auto-open on ingest",
+ className,
+}: {
+ value: IngestPreviewAutoOpen;
+ onChange: (value: IngestPreviewAutoOpen) => void;
+ "aria-label"?: string;
+ className?: string;
+}) {
+ const isCloudBrand = useIsCloudBrand();
+
+ return (
+ <Tabs
+ value={value}
+ onValueChange={(next) => onChange(next as IngestPreviewAutoOpen)}
+ className={className}
+ >
+ <TabsList
+ variant="default"
+ aria-label={ariaLabel}
+ className={cn(
+ "h-auto shrink-0 border border-border p-0.5",
+ isCloudBrand ? "!rounded-none overflow-hidden" : "rounded-md",
+ )}
+ >
+ {INGEST_PREVIEW_AUTO_OPEN_OPTIONS.map((option) => (
+ <TabsTrigger
+ key={option.value}
+ value={option.value}
+ className={cn(
+ "px-3 py-1.5 text-xs sm:text-sm",
+ isCloudBrand &&
+ "!rounded-none dark:hover:!bg-[#F4F4F4] dark:hover:!text-neutral-900 dark:data-[state=active]:!bg-[#F4F4F4] dark:data-[state=active]:!text-neutral-900",
+ )}
+ >
+ {option.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ );
+}
diff --git a/frontend/components/ingest-review.tsx b/frontend/components/ingest-review.tsx
new file mode 100644
index 000000000..4e2aa2137
--- /dev/null
+++ b/frontend/components/ingest-review.tsx
@@ -0,0 +1,1470 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import {
+ Check,
+ ChevronDown,
+ ChevronUp,
+ Circle,
+ FileIcon,
+ Loader2,
+ Maximize2,
+ Minimize2,
+ X,
+} from "lucide-react";
+import { useEffect, useId, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import {
+ type Task,
+ type TaskFileEntry,
+ useGetTasksQuery,
+} from "@/app/api/queries/useGetTasksQuery";
+import {
+ type DoclingPreviewResponse,
+ type IndexProofChunk,
+ ingestPreviewQueryKeys,
+ useDoclingPreviewQuery,
+ useIndexProofQuery,
+} from "@/app/api/queries/useIngestPreviewQuery";
+import {
+ DoclingParseViewer,
+ DoclingTextPreview,
+} from "@/components/docling-preview";
+import { FileChunksPanel } from "@/components/file-chunks-panel";
+import { IngestPreviewAutoOpenControl } from "@/components/ingest-preview-auto-open-control";
+import { KnowledgeSearchInput } from "@/components/knowledge-search-input";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useTask } from "@/contexts/task-context";
+import {
+ type IngestPreviewSettings,
+ useIngestPreviewSettings,
+} from "@/hooks/use-ingest-preview-settings";
+import {
+ doclingHasPageImages,
+ matchChunkToDoclingItems,
+ summarizeChunkPages,
+} from "@/lib/ingest-preview";
+import {
+ buildSampleDemoDocument,
+ SAMPLE_DEMO_CHUNKS,
+ SAMPLE_DEMO_FILENAME,
+ SAMPLE_DEMO_STATS,
+} from "@/lib/ingest-preview-demo";
+import { cn } from "@/lib/utils";
+
+/** Client-only walkthrough phases for “Run a sample ingest” (nothing is uploaded). */
+function useDemoPreviewPhase(enabled: boolean): number {
+ const [phase, setPhase] = useState(0);
+ const [prevEnabled, setPrevEnabled] = useState(enabled);
+
+ // Reset inline when `enabled` flips so we never paint a stale phase.
+ // https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
+ if (enabled !== prevEnabled) {
+ setPrevEnabled(enabled);
+ setPhase(0);
+ }
+
+ useEffect(() => {
+ if (!enabled) return;
+ const delays = [500, 1100, 1700, 2300];
+ const timers = delays.map((ms, index) =>
+ setTimeout(() => setPhase(index + 1), ms),
+ );
+ return () => {
+ for (const timer of timers) clearTimeout(timer);
+ };
+ }, [enabled]);
+ return phase;
+}
+
+/**
+ * Live index-proof returns chunks + embeddings + ready together. Reveal the
+ * last three pipeline steps ~700ms apart so they don't all check off at once.
+ * Returns how many of those steps to show as done (0–3).
+ */
+function useStaggeredPostLayoutReveal(
+ enabled: boolean,
+ resetKey: string,
+): number {
+ const [revealed, setRevealed] = useState(0);
+ const [prevResetKey, setPrevResetKey] = useState(resetKey);
+ const [prevEnabled, setPrevEnabled] = useState(enabled);
+
+ // Reset inline when the file or stagger gate flips — avoid a stale paint.
+ // https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
+ if (resetKey !== prevResetKey) {
+ setPrevResetKey(resetKey);
+ setRevealed(0);
+ }
+ if (enabled !== prevEnabled) {
+ setPrevEnabled(enabled);
+ setRevealed(0);
+ }
+
+ useEffect(() => {
+ if (!enabled) return;
+ // First step stays "active" briefly, then each completes in sequence.
+ const delays = [700, 1400, 2100];
+ const timers = delays.map((ms, index) =>
+ setTimeout(() => setRevealed(index + 1), ms),
+ );
+ return () => {
+ for (const timer of timers) clearTimeout(timer);
+ };
+ }, [enabled, resetKey]);
+
+ return revealed;
+}
+
+function previewFrameClass(expanded: boolean): string {
+ return cn(
+ "overflow-auto rounded-md bg-background",
+ // Fixed height in dialog mode so skeleton → Docling swap does not jump.
+ expanded
+ ? "h-full min-h-0 max-h-none"
+ : "h-[420px] min-h-[420px] max-h-[420px]",
+ );
+}
+
+function isFileEntryFailed(entry?: TaskFileEntry): boolean {
+ return entry?.status === "failed" || entry?.status === "error";
+}
+
+/** A file is viewable once Docling has finished (phase past docling). */
+function isPreviewReady(entry?: TaskFileEntry): boolean {
+ return entry?.phase === "langflow" || entry?.phase === "complete";
+}
+
+// --- Left column: the original document -------------------------------------
+
+function SkeletonChunk({
+ label,
+ lines,
+ active = false,
+ className,
+}: {
+ label: string;
+ lines: ReadonlyArray<{ id: string; width: string }>;
+ /** Emphasized chunk (thicker border + stronger badge), matching the design mock. */
+ active?: boolean;
+ className?: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "relative rounded-md border-dashed bg-transparent p-3 pt-4",
+ active
+ ? "border-2 border-sky-500 dark:border-sky-400"
+ : "border border-sky-300/70 dark:border-sky-500/35",
+ className,
+ )}
+ >
+ <span
+ className={cn(
+ "absolute -top-2.5 left-2 rounded-full px-2 py-0.5 text-[10px] font-medium leading-none text-white",
+ active ? "bg-sky-500" : "bg-sky-400/80 dark:bg-sky-500/70",
+ )}
+ >
+ {label}
+ </span>
+ <div className="flex flex-col gap-2">
+ {lines.map((line) => (
+ <Skeleton
+ key={line.id}
+ className={cn(
+ "h-2 rounded-full bg-muted-foreground/20 dark:bg-muted-foreground/25",
+ line.width,
+ )}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** Placeholder DocPage layout while Docling parse preview is loading. */
+function DoclingDocSkeleton({ expanded = false }: { expanded?: boolean }) {
+ return (
+ <div
+ className={cn(
+ previewFrameClass(expanded),
+ "bg-muted/40 p-3",
+ expanded && "min-h-0 flex-1",
+ )}
+ data-testid="ingest-review-doc-skeleton"
+ aria-busy="true"
+ aria-label="Loading document layout"
+ >
+ <div className="min-h-full rounded-lg border border-border/60 bg-background p-4 shadow-sm space-y-5">
+ <SkeletonChunk
+ label="Header"
+ lines={[
+ { id: "h1", width: "w-3/5" },
+ { id: "h2", width: "w-2/5" },
+ { id: "h3", width: "w-1/2" },
+ ]}
+ />
+ <SkeletonChunk
+ label="Chunk 1"
+ active
+ lines={[
+ { id: "c1a", width: "w-full" },
+ { id: "c1b", width: "w-5/6" },
+ { id: "c1c", width: "w-full" },
+ { id: "c1d", width: "w-4/5" },
+ { id: "c1e", width: "w-full" },
+ { id: "c1f", width: "w-5/6" },
+ { id: "c1g", width: "w-2/3" },
+ ]}
+ />
+ <SkeletonChunk
+ label="Chunk 2"
+ lines={[
+ { id: "c2a", width: "w-full" },
+ { id: "c2b", width: "w-5/6" },
+ { id: "c2c", width: "w-full" },
+ { id: "c2d", width: "w-4/5" },
+ { id: "c2e", width: "w-3/5" },
+ ]}
+ />
+ <p className="pt-1 text-right text-xs text-muted-foreground/60">1</p>
+ </div>
+ </div>
+ );
+}
+
+function DocumentPane({
+ failed,
+ failureMessage,
+ parsePreview,
+ highlightItemRefs,
+ fallbackPage,
+ highlightText,
+ chunkLabel,
+ hasChunks,
+ expanded = false,
+ waitingForDocument = true,
+ onRetryPreview,
+}: {
+ failed: boolean;
+ failureMessage: string;
+ parsePreview: DoclingPreviewResponse | null | undefined;
+ highlightItemRefs?: string[];
+ fallbackPage?: number | null;
+ highlightText?: string;
+ chunkLabel?: string;
+ hasChunks: boolean;
+ expanded?: boolean;
+ /** Still polling Docling cache (404/null). False once exhausted or errored. */
+ waitingForDocument?: boolean;
+ onRetryPreview?: () => void;
+}) {
+ const doclingDocument = parsePreview?.document;
+ const frameClass = previewFrameClass(expanded);
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
+
+ if (failed) {
+ return (
+ <div
+ className="flex h-56 flex-col items-center justify-center gap-2 px-4 text-center text-muted-foreground"
+ data-testid="ingest-review-failed"
+ >
+ <p className="text-md font-medium text-destructive">Parsing failed</p>
+ <p className="text-xs">{failureMessage}</p>
+ </div>
+ );
+ }
+
+ if (doclingDocument) {
+ if (doclingHasPageImages(doclingDocument)) {
+ return (
+ <div
+ ref={scrollContainerRef}
+ className={cn(frameClass, expanded && "min-h-0 flex-1")}
+ >
+ <p className="mb-2 shrink-0 text-xs text-muted-foreground">
+ Blue boxes mark parsed text, tables, and figures.
+ {hasChunks ? " Click a chunk to focus its region." : null}
+ </p>
+ <DoclingParseViewer
+ doclingDocument={doclingDocument}
+ highlightItemRefs={highlightItemRefs}
+ fallbackPage={fallbackPage}
+ chunkLabel={chunkLabel}
+ scrollContainerRef={scrollContainerRef}
+ />
+ </div>
+ );
+ }
+ return (
+ <div
+ ref={scrollContainerRef}
+ className={cn(frameClass, expanded && "min-h-0 flex-1")}
+ >
+ <p className="mb-2 shrink-0 text-xs text-muted-foreground">
+ No page image for this format — each region Docling detected is boxed
+ and labeled by type.
+ {hasChunks ? " Click a chunk to focus its region." : null}
+ </p>
+ <DoclingTextPreview
+ doclingDocument={doclingDocument}
+ highlightItemRefs={highlightItemRefs}
+ highlightText={highlightText}
+ chunkLabel={chunkLabel}
+ />
+ </div>
+ );
+ }
+
+ if (waitingForDocument) {
+ return <DoclingDocSkeleton expanded={expanded} />;
+ }
+
+ return (
+ <div
+ className="flex h-56 flex-col items-center justify-center gap-3 px-4 text-center text-muted-foreground"
+ data-testid="ingest-review-doc-unavailable"
+ >
+ <p className="text-md font-medium text-foreground">
+ Document preview unavailable
+ </p>
+ <p className="text-xs">
+ Ingest may have finished, but the parse preview never arrived. You can
+ retry or close this dialog — the file is still searchable if indexing
+ completed.
+ </p>
+ {onRetryPreview ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onRetryPreview}
+ data-testid="ingest-review-doc-retry"
+ >
+ Retry preview
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
+// --- Right column: indexing pipeline + chunks -------------------------------
+
+interface PipelineStep {
+ id: string;
+ done: boolean;
+ label: string;
+}
+
+function ProofLine({
+ done,
+ label,
+ failed,
+ idle,
+}: {
+ done: boolean;
+ label: string;
+ failed: boolean;
+ idle: boolean;
+}) {
+ return (
+ <li className="flex items-center gap-2.5">
+ {failed ? (
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-destructive">
+ <X className="h-3 w-3 text-destructive-foreground" />
+ </span>
+ ) : done ? (
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[rgb(0_188_125/0.15)]">
+ <Check className="h-3 w-3 text-[rgb(0_188_125)]" strokeWidth={3} />
+ </span>
+ ) : idle ? (
+ <Circle className="h-5 w-5 shrink-0 text-muted-foreground/40" />
+ ) : (
+ <Loader2 className="h-5 w-5 shrink-0 animate-spin text-blue-500" />
+ )}
+ <span
+ className={cn(
+ "text-sm",
+ failed
+ ? "text-destructive"
+ : done
+ ? "text-foreground"
+ : "text-muted-foreground",
+ )}
+ >
+ {label}
+ </span>
+ </li>
+ );
+}
+
+function DemoChunksList({
+ chunks,
+ showContents,
+ chunkSearch,
+ selectedChunkIndex,
+ onSelectChunk,
+ expanded = false,
+}: {
+ chunks: IndexProofChunk[];
+ showContents: boolean;
+ chunkSearch: string;
+ selectedChunkIndex?: number | null;
+ onSelectChunk: (chunk: {
+ index: number;
+ page: number | null;
+ text: string;
+ }) => void;
+ expanded?: boolean;
+}) {
+ // Number in source order before filtering so search does not renumber Chunk N.
+ const numbered = chunks.map((chunk, index) => ({
+ ...chunk,
+ displayIndex: index + 1,
+ }));
+ const needle = chunkSearch.trim().toLowerCase();
+ const visible = needle
+ ? numbered.filter((chunk) =>
+ chunk.text_preview.toLowerCase().includes(needle),
+ )
+ : numbered;
+
+ if (visible.length === 0) {
+ return (
+ <p className="text-xs text-muted-foreground">
+ No chunks match your search.
+ </p>
+ );
+ }
+
+ return (
+ <div
+ className={cn(
+ "space-y-3 overflow-auto",
+ expanded ? "min-h-0 flex-1" : "max-h-72",
+ )}
+ data-testid="ingest-review-demo-chunks"
+ >
+ {visible.map((chunk) => {
+ const chunkIndex = chunk.displayIndex;
+ const selected = selectedChunkIndex === chunkIndex;
+ return (
+ <button
+ key={chunk.chunk_id}
+ type="button"
+ className={cn(
+ "w-full rounded-lg border border-border/50 bg-muted p-2.5 text-left transition-colors hover:border-primary/40",
+ selected && "border-primary/60 ring-1 ring-primary/30",
+ )}
+ onClick={() =>
+ onSelectChunk({
+ index: chunkIndex,
+ page: chunk.page ?? null,
+ text: chunk.text_preview,
+ })
+ }
+ >
+ <div className="mb-2 flex min-w-0 flex-wrap items-center gap-2">
+ <span className="text-xs font-bold">Chunk {chunkIndex}</span>
+ <Badge variant="secondary" className="text-xxs">
+ {chunk.char_count} chars
+ </Badge>
+ </div>
+ {showContents ? (
+ <blockquote className="min-w-0 text-xs text-muted-foreground leading-relaxed break-words [overflow-wrap:anywhere] whitespace-pre-wrap">
+ {chunk.text_preview}
+ </blockquote>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ {chunk.page != null ? `page ${chunk.page}` : "chunk"} ·{" "}
+ {chunk.char_count} chars
+ </p>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+function IndexPane({
+ steps,
+ filename,
+ showIndexingPipeline,
+ showChunkBoundaries,
+ showChunkContents,
+ failed,
+ failedStepIndex,
+ failureMessage,
+ onViewError,
+ awaitingChunks,
+ selectedChunkIndex,
+ onSelectChunk,
+ chunkSearch,
+ onChunkSearchChange,
+ demoChunks,
+ expanded = false,
+}: {
+ steps: PipelineStep[];
+ filename: string | undefined;
+ showIndexingPipeline: boolean;
+ showChunkBoundaries: boolean;
+ showChunkContents: boolean;
+ failed: boolean;
+ failedStepIndex: number;
+ failureMessage: string;
+ onViewError?: () => void;
+ awaitingChunks: boolean;
+ selectedChunkIndex?: number | null;
+ onSelectChunk: (chunk: {
+ index: number;
+ page: number | null;
+ text: string;
+ }) => void;
+ chunkSearch: string;
+ onChunkSearchChange: (query: string) => void;
+ demoChunks?: IndexProofChunk[];
+ expanded?: boolean;
+}) {
+ const activeStepIndex = failed ? -1 : steps.findIndex((step) => !step.done);
+
+ return (
+ <div
+ className={cn(
+ "flex min-h-[280px] flex-col rounded-lg border border-border/60 bg-muted/30 p-4",
+ expanded && "h-full min-h-0",
+ )}
+ >
+ {showIndexingPipeline && (
+ <div className="shrink-0">
+ <h3 className="mb-3 text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ Index details
+ </h3>
+ <ul className="mb-4 space-y-3">
+ {steps.map((step, i) => {
+ const isFailed = failed && i === failedStepIndex;
+ const isActive = !failed && i === activeStepIndex;
+ const isIdle =
+ (failed && i > failedStepIndex && !step.done) ||
+ (!failed && i > activeStepIndex && !step.done);
+ return (
+ <ProofLine
+ key={step.id}
+ done={step.done && !isFailed}
+ failed={isFailed}
+ idle={isIdle && !isActive}
+ label={isFailed ? failureMessage : step.label}
+ />
+ );
+ })}
+ </ul>
+ </div>
+ )}
+
+ {failed && onViewError && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="mb-4 w-full shrink-0"
+ data-testid="ingest-review-view-error"
+ onClick={onViewError}
+ >
+ View error details &amp; retry
+ </Button>
+ )}
+
+ {showIndexingPipeline && showChunkBoundaries && (
+ <div className="mb-4 shrink-0 border-t border-border/60" />
+ )}
+
+ {showChunkBoundaries && filename && !awaitingChunks && demoChunks && (
+ <div className={cn(expanded && "min-h-0 flex-1")}>
+ <DemoChunksList
+ chunks={demoChunks}
+ showContents={showChunkContents}
+ chunkSearch={chunkSearch}
+ selectedChunkIndex={selectedChunkIndex}
+ onSelectChunk={onSelectChunk}
+ expanded={expanded}
+ />
+ </div>
+ )}
+
+ {showChunkBoundaries && filename && !awaitingChunks && !demoChunks && (
+ <div className={cn(expanded && "min-h-0 flex-1")}>
+ <FileChunksPanel
+ filename={filename}
+ compact
+ fillHeight={expanded}
+ showContents={showChunkContents}
+ selectedChunkIndex={selectedChunkIndex}
+ hideSearch
+ filterQuery={chunkSearch}
+ onFilterQueryChange={onChunkSearchChange}
+ onChunkSelect={(chunk) => {
+ onSelectChunk({
+ index: chunk.index ?? 0,
+ page: chunk.page ?? null,
+ text: chunk.text,
+ });
+ }}
+ />
+ </div>
+ )}
+
+ {showChunkBoundaries && awaitingChunks && !failed && (
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ Waiting for chunks…
+ </div>
+ )}
+ </div>
+ );
+}
+
+// --- File selector ----------------------------------------------------------
+
+interface CarouselFile {
+ taskId: string | null;
+ filePath: string | null;
+ entry?: TaskFileEntry;
+ filename: string;
+}
+
+function fileSelectionKey(file: CarouselFile): string {
+ return `${file.taskId ?? "local"}:${file.filePath ?? file.filename}`;
+}
+
+function PreviewFileSelector({
+ files,
+ activeIndex,
+ onSelect,
+}: {
+ files: CarouselFile[];
+ activeIndex: number;
+ onSelect: (index: number) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const listboxId = useId();
+ const active = files[activeIndex];
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ role="combobox"
+ aria-expanded={open}
+ aria-controls={listboxId}
+ className="h-auto w-full min-w-0 justify-between gap-2 px-1.5 py-2 font-medium hover:bg-muted/60"
+ data-testid="ingest-review-file-selector"
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
+ <FileIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="truncate" title={active?.filename}>
+ {active?.filename ?? "Select file"}
+ </span>
+ </span>
+ {open ? (
+ <ChevronUp className="h-3.5 w-3.5 shrink-0 opacity-50" />
+ ) : (
+ <ChevronDown className="h-3.5 w-3.5 shrink-0 opacity-50" />
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="min-w-[260px] w-[var(--radix-popover-trigger-width)] p-0"
+ align="start"
+ >
+ <Command>
+ <CommandInput placeholder="Search files…" />
+ <CommandList id={listboxId}>
+ <CommandEmpty>No files found.</CommandEmpty>
+ <CommandGroup>
+ {files.map((file, index) => {
+ const key = fileSelectionKey(file);
+ const failed = isFileEntryFailed(file.entry);
+ const ready = !failed && isPreviewReady(file.entry);
+ const status = failed
+ ? "failed"
+ : ready
+ ? "ready"
+ : "processing";
+ return (
+ <CommandItem
+ key={key}
+ value={key}
+ keywords={[file.filename]}
+ onSelect={() => {
+ onSelect(index);
+ setOpen(false);
+ }}
+ className="min-w-0 gap-2 overflow-hidden"
+ >
+ <Check
+ className={cn(
+ "h-4 w-4 shrink-0",
+ index === activeIndex ? "opacity-100" : "opacity-0",
+ )}
+ />
+ <span
+ className="min-w-0 flex-1 truncate"
+ title={file.filename}
+ >
+ {file.filename}
+ </span>
+ <span
+ className={cn(
+ "shrink-0 text-xs",
+ failed
+ ? "text-destructive"
+ : ready
+ ? "text-emerald-600 dark:text-emerald-400"
+ : "text-muted-foreground",
+ )}
+ >
+ {status}
+ </span>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+// --- Content container -------------------------------------------------------
+
+/**
+ * Flatten the files of every task into one ordered list. Folder uploads split
+ * into several batch tasks, so the review spans them as one continuous set.
+ */
+function carouselFilesFromTasks(
+ tasks: Task[] | undefined,
+ taskIds: string[],
+): CarouselFile[] {
+ if (!tasks || taskIds.length === 0) return [];
+ const tasksById = new Map(tasks.map((task) => [task.task_id, task]));
+ const files: CarouselFile[] = [];
+ for (const id of taskIds) {
+ const task = tasksById.get(id);
+ if (!task?.files) continue;
+ for (const [filePath, entry] of Object.entries(task.files)) {
+ files.push({
+ taskId: task.task_id,
+ filePath,
+ entry,
+ filename: entry.filename ?? filePath.split("/").pop() ?? filePath,
+ });
+ }
+ }
+ return files;
+}
+
+const FAILURE_PHASE_TO_STEP: Record<string, number> = {
+ parsing: 0,
+ file_validation: 0,
+ chunking: 1,
+ embedding: 2,
+ indexing: 3,
+};
+
+type ChunkHighlight = {
+ index: number;
+ page: number | null;
+ text: string;
+};
+
+function useIngestCompletionToast({
+ demo,
+ ready,
+ completionNotification,
+ activeFilename,
+ activeSelectionKey,
+}: {
+ demo: boolean;
+ ready: boolean;
+ completionNotification: boolean;
+ activeFilename: string | undefined;
+ activeSelectionKey: string;
+}) {
+ const notifiedRef = useRef<Set<string> | null>(null);
+ if (notifiedRef.current === null) {
+ notifiedRef.current = new Set();
+ }
+
+ useEffect(() => {
+ if (demo || !completionNotification || !ready || !activeFilename) {
+ return;
+ }
+ const key = activeSelectionKey || activeFilename;
+ const notified = notifiedRef.current;
+ if (!notified || notified.has(key)) return;
+ notified.add(key);
+ toast.success("Task completed", {
+ description: `${activeFilename} is indexed and searchable.`,
+ });
+ }, [demo, ready, completionNotification, activeFilename, activeSelectionKey]);
+}
+
+function useIngestReviewModel({
+ taskIds,
+ previewFiles,
+ demo,
+ settingsOverride,
+}: {
+ taskIds: string[];
+ previewFiles?: File[];
+ demo: boolean;
+ settingsOverride?: IngestPreviewSettings;
+}) {
+ const { settings: storedSettings, updateSettings } =
+ useIngestPreviewSettings();
+ const settings = settingsOverride ?? storedSettings;
+ const { data: tasks } = useGetTasksQuery({
+ enabled: !demo && taskIds.length > 0,
+ });
+ const demoPhase = useDemoPreviewPhase(demo);
+ const demoDocument = useMemo(
+ () => (demo ? buildSampleDemoDocument() : null),
+ [demo],
+ );
+
+ const fromTasks = carouselFilesFromTasks(tasks, taskIds);
+ const files: CarouselFile[] =
+ fromTasks.length > 0
+ ? fromTasks
+ : (previewFiles ?? []).length > 0
+ ? (previewFiles ?? []).map((file) => ({
+ taskId: null,
+ filePath: null,
+ filename: file.name,
+ }))
+ : demo
+ ? [
+ {
+ taskId: null,
+ filePath: null,
+ filename: SAMPLE_DEMO_FILENAME,
+ },
+ ]
+ : [];
+
+ // Stable across task polls / late-arriving folder batches (not a list index).
+ const [selectedKey, setSelectedKey] = useState<string | null>(null);
+ const selectedIndex = selectedKey
+ ? files.findIndex((f) => fileSelectionKey(f) === selectedKey)
+ : -1;
+ const activeIndex = selectedIndex >= 0 ? selectedIndex : 0;
+
+ const active = files[activeIndex];
+ const activeTaskId = demo ? null : (active?.taskId ?? taskIds[0] ?? null);
+
+ const failed = !demo && isFileEntryFailed(active?.entry);
+ const activeFilePath = active?.filePath ?? null;
+ const queryClient = useQueryClient();
+ const previewReady = !demo && isPreviewReady(active?.entry);
+
+ const {
+ data: liveParsePreview,
+ isFetching: parsePreviewFetching,
+ isPending: parsePreviewPending,
+ isError: parsePreviewError,
+ refetch: refetchParsePreview,
+ } = useDoclingPreviewQuery(
+ activeTaskId,
+ Boolean(activeTaskId) && !failed,
+ activeFilePath,
+ );
+ const { data: liveIndexProof } = useIndexProofQuery(
+ activeTaskId,
+ Boolean(activeTaskId) && !failed,
+ activeFilePath,
+ );
+
+ // No Docling interval poll. useQuery fetches on mount / query-key change;
+ // invalidate only when phase or preview-ready *transitions* while we still
+ // lack a document (avoids a mount double-fetch and effect cascades).
+ const filePhase = active?.entry?.phase;
+ const phaseReadyKey = `${activeTaskId ?? ""}:${activeFilePath ?? ""}:${filePhase ?? ""}:${previewReady}`;
+ const prevPhaseReadyKeyRef = useRef<string | null>(null);
+ useEffect(() => {
+ const prev = prevPhaseReadyKeyRef.current;
+ prevPhaseReadyKeyRef.current = phaseReadyKey;
+ if (prev === null || prev === phaseReadyKey) return;
+ if (!activeTaskId || failed || liveParsePreview?.document) return;
+ void queryClient.invalidateQueries({
+ queryKey: ingestPreviewQueryKeys.docling(activeTaskId, activeFilePath),
+ });
+ }, [
+ phaseReadyKey,
+ activeTaskId,
+ activeFilePath,
+ failed,
+ liveParsePreview?.document,
+ queryClient,
+ ]);
+
+ const parsePreview: DoclingPreviewResponse | null | undefined = demo
+ ? demoPhase >= 1 && demoDocument
+ ? {
+ task_id: "demo",
+ document: demoDocument,
+ stats: SAMPLE_DEMO_STATS,
+ expires_at: 0,
+ filename: active?.filename,
+ }
+ : null
+ : liveParsePreview;
+
+ const indexProof = demo
+ ? {
+ ready: demoPhase >= 4,
+ chunk_count: demoPhase >= 2 ? SAMPLE_DEMO_CHUNKS.length : 0,
+ embedding_dimensions: demoPhase >= 3 ? 1536 : undefined,
+ chunks: demoPhase >= 2 ? SAMPLE_DEMO_CHUNKS : [],
+ }
+ : liveIndexProof;
+
+ const [chunkHighlight, setChunkHighlight] = useState<ChunkHighlight | null>(
+ null,
+ );
+ const [chunkSearch, setChunkSearch] = useState("");
+ const activeSelectionKey = active ? fileSelectionKey(active) : "";
+ const [prevActiveSelectionKey, setPrevActiveSelectionKey] =
+ useState(activeSelectionKey);
+ if (activeSelectionKey !== prevActiveSelectionKey) {
+ setPrevActiveSelectionKey(activeSelectionKey);
+ setChunkHighlight(null);
+ setChunkSearch("");
+ }
+
+ const showChunks = settings.showChunkBoundaries;
+ const { numbering: pageNumbering } = summarizeChunkPages(
+ indexProof?.chunks ?? [],
+ );
+
+ const doclingMatch = useMemo(() => {
+ if (!chunkHighlight) return null;
+ return matchChunkToDoclingItems(
+ parsePreview?.document,
+ { page: chunkHighlight.page, text: chunkHighlight.text },
+ pageNumbering,
+ );
+ }, [chunkHighlight, parsePreview?.document, pageNumbering]);
+
+ const highlightItemRefs = doclingMatch?.itemRefs;
+ // Prefer the page from text→item match (indexed chunk.page is often wrong).
+ // Fall back to the chunk's page so PDF overlays still have a scroll target.
+ const fallbackPage =
+ doclingMatch?.page ??
+ (chunkHighlight?.page != null
+ ? pageNumbering === "zero-based"
+ ? chunkHighlight.page + 1
+ : chunkHighlight.page
+ : null);
+ const chunkLabel =
+ chunkHighlight != null ? `Chunk ${chunkHighlight.index}` : undefined;
+
+ const doclingFinished = demo ? demoPhase >= 1 : previewReady;
+ const layoutReady = Boolean(parsePreview?.document);
+ // Skeleton while ingest is still parsing, or while a fetch/retry is in flight.
+ // Once preview-ready and settled with no document → unavailable + retry.
+ const waitingForDocument = demo
+ ? demoPhase < 1
+ : Boolean(activeTaskId) &&
+ !failed &&
+ !parsePreview?.document &&
+ (!previewReady ||
+ parsePreviewPending ||
+ parsePreviewFetching ||
+ (liveParsePreview === undefined && !parsePreviewError));
+ const retryParsePreview = () => {
+ if (!activeTaskId) return;
+ void queryClient.invalidateQueries({
+ queryKey: ingestPreviewQueryKeys.docling(activeTaskId, activeFilePath),
+ });
+ void refetchParsePreview();
+ };
+ const chunkCount = indexProof?.chunk_count ?? 0;
+ const embeddingsReady = Boolean(indexProof?.embedding_dimensions);
+ const storedReady = Boolean(indexProof?.ready);
+ // Index-proof is atomic after COMPLETE — stagger only the live UI reveal.
+ const proofComplete = chunkCount > 0 && embeddingsReady && storedReady;
+ const staggerReveal = useStaggeredPostLayoutReveal(
+ !demo && !failed && proofComplete,
+ activeSelectionKey,
+ );
+ const chunksDone =
+ chunkCount > 0 && (demo || failed || !proofComplete || staggerReveal >= 1);
+ const embeddingsDone =
+ embeddingsReady && (demo || failed || !proofComplete || staggerReveal >= 2);
+ const storedDone =
+ storedReady && (demo || failed || !proofComplete || staggerReveal >= 3);
+ const steps: PipelineStep[] = [
+ {
+ id: "layout",
+ done: layoutReady || doclingFinished,
+ label: "Reading layout",
+ },
+ { id: "chunks", done: chunksDone, label: "Creating chunks" },
+ {
+ id: "embeddings",
+ done: embeddingsDone,
+ label: "Generating embeddings",
+ },
+ {
+ id: "stored",
+ done: storedDone,
+ label: demo ? "Ready for retrieval" : "Stored in OpenSearch",
+ },
+ ];
+
+ const failureMessage =
+ active?.entry?.user_facing_message ||
+ active?.entry?.error ||
+ "Ingestion failed. Please try again.";
+ let failedStepIndex = -1;
+ if (failed) {
+ const failurePhase = active?.entry?.failure_phase;
+ if (failurePhase && failurePhase in FAILURE_PHASE_TO_STEP) {
+ failedStepIndex = FAILURE_PHASE_TO_STEP[failurePhase];
+ } else {
+ const firstNotDone = steps.findIndex((s) => !s.done);
+ failedStepIndex = firstNotDone === -1 ? steps.length - 1 : firstNotDone;
+ }
+ }
+
+ const activeFilename = active?.filename;
+ useIngestCompletionToast({
+ demo,
+ ready: Boolean(indexProof?.ready),
+ completionNotification: settings.completionNotification,
+ activeFilename,
+ activeSelectionKey,
+ });
+
+ return {
+ settings,
+ updateSettings,
+ files,
+ activeIndex,
+ setSelectedKey,
+ activeTaskId,
+ failed,
+ parsePreview,
+ waitingForDocument,
+ retryParsePreview,
+ chunkHighlight,
+ setChunkHighlight,
+ chunkSearch,
+ setChunkSearch,
+ showChunks,
+ highlightItemRefs,
+ fallbackPage,
+ chunkLabel,
+ chunkCount,
+ steps,
+ failureMessage,
+ failedStepIndex,
+ activeFilename,
+ };
+}
+
+function IngestReviewToolbar({
+ files,
+ activeIndex,
+ activeFilename,
+ parsePreview,
+ showChunks,
+ chunkSearch,
+ onSelectFile,
+ onChunkSearch,
+ onClearChunkSearch,
+}: {
+ files: CarouselFile[];
+ activeIndex: number;
+ activeFilename: string | undefined;
+ parsePreview: DoclingPreviewResponse | null | undefined;
+ showChunks: boolean;
+ chunkSearch: string;
+ onSelectFile: (index: number) => void;
+ onChunkSearch: (query: string) => void;
+ onClearChunkSearch: () => void;
+}) {
+ const canNavigate = files.length > 1;
+
+ return (
+ <div className="-mx-4 shrink-0 grid items-center gap-3 border-t border-b border-border px-4 lg:grid-cols-2 lg:gap-0">
+ <div className="flex min-w-0 items-center gap-x-4 lg:pr-4">
+ {canNavigate ? (
+ <div className="min-w-0 flex-1">
+ <PreviewFileSelector
+ files={files}
+ activeIndex={activeIndex}
+ onSelect={onSelectFile}
+ />
+ </div>
+ ) : (
+ <span
+ className="inline-flex min-w-0 flex-1 items-center gap-2 text-sm font-medium"
+ title={activeFilename}
+ >
+ <FileIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="truncate">{activeFilename ?? "Document"}</span>
+ </span>
+ )}
+
+ {parsePreview?.stats && (
+ <span className="shrink-0 whitespace-nowrap text-xs text-muted-foreground">
+ {parsePreview.stats.text_count} text ·{" "}
+ {parsePreview.stats.table_count} tables ·{" "}
+ {parsePreview.stats.picture_count} figures
+ </span>
+ )}
+ </div>
+
+ {showChunks && activeFilename ? (
+ <div className="flex min-w-0 items-center border-border p-2 lg:border-l">
+ <KnowledgeSearchInput
+ value={chunkSearch}
+ onSearch={onChunkSearch}
+ onClear={onClearChunkSearch}
+ hideFilterChip
+ hideSubmit
+ placeholder="Search chunks…"
+ className="max-w-none w-full"
+ inputClassName="rounded-full !min-h-9"
+ />
+ </div>
+ ) : (
+ <div className="hidden lg:block" />
+ )}
+ </div>
+ );
+}
+
+function IngestReviewDocumentColumn({
+ failed,
+ failureMessage,
+ parsePreview,
+ highlightItemRefs,
+ fallbackPage,
+ highlightText,
+ chunkLabel,
+ hasChunks,
+ expanded,
+ waitingForDocument,
+ onRetryPreview,
+}: {
+ failed: boolean;
+ failureMessage: string;
+ parsePreview: DoclingPreviewResponse | null | undefined;
+ highlightItemRefs?: string[];
+ fallbackPage?: number | null;
+ highlightText?: string;
+ chunkLabel?: string;
+ hasChunks: boolean;
+ expanded: boolean;
+ waitingForDocument: boolean;
+ onRetryPreview: () => void;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex min-h-[280px] flex-col rounded-lg border border-border/60 bg-muted/30 p-3",
+ expanded && "h-full min-h-0",
+ )}
+ >
+ <h3 className="mb-2 shrink-0 text-sm font-semibold">Document</h3>
+ <div
+ className={cn("min-h-0", expanded ? "flex flex-1 flex-col" : undefined)}
+ >
+ <DocumentPane
+ failed={failed}
+ failureMessage={failureMessage}
+ parsePreview={parsePreview}
+ highlightItemRefs={highlightItemRefs}
+ fallbackPage={fallbackPage}
+ highlightText={highlightText}
+ chunkLabel={chunkLabel}
+ hasChunks={hasChunks}
+ expanded={expanded}
+ waitingForDocument={waitingForDocument}
+ onRetryPreview={onRetryPreview}
+ />
+ </div>
+ </div>
+ );
+}
+
+function IngestReviewAutoOpenFooter({
+ autoOpen,
+ onAutoOpenChange,
+}: {
+ autoOpen: IngestPreviewSettings["autoOpen"];
+ onAutoOpenChange: (autoOpen: IngestPreviewSettings["autoOpen"]) => void;
+}) {
+ return (
+ <div className="mt-3 flex shrink-0 flex-wrap items-center gap-3">
+ <span className="text-sm text-muted-foreground">Auto-open on ingest</span>
+ <IngestPreviewAutoOpenControl
+ value={autoOpen}
+ onChange={onAutoOpenChange}
+ />
+ </div>
+ );
+}
+
+function IngestReviewContent({
+ taskIds,
+ previewFiles,
+ demo = false,
+ settingsOverride,
+ showAutoOpenFooter = false,
+ onViewError,
+ expanded = false,
+}: {
+ taskIds: string[];
+ previewFiles?: File[];
+ demo?: boolean;
+ /** When set (e.g. unsaved settings draft), prefer over persisted prefs. */
+ settingsOverride?: IngestPreviewSettings;
+ /** Auto-open control — onboarding only. */
+ showAutoOpenFooter?: boolean;
+ onViewError?: (taskId: string) => void;
+ expanded?: boolean;
+}) {
+ const {
+ settings,
+ updateSettings,
+ files,
+ activeIndex,
+ setSelectedKey,
+ activeTaskId,
+ failed,
+ parsePreview,
+ waitingForDocument,
+ retryParsePreview,
+ chunkHighlight,
+ setChunkHighlight,
+ chunkSearch,
+ setChunkSearch,
+ showChunks,
+ highlightItemRefs,
+ fallbackPage,
+ chunkLabel,
+ chunkCount,
+ steps,
+ failureMessage,
+ failedStepIndex,
+ activeFilename,
+ } = useIngestReviewModel({
+ taskIds,
+ previewFiles,
+ demo,
+ settingsOverride,
+ });
+
+ return (
+ <div
+ className="flex min-h-0 flex-1 flex-col"
+ data-testid="ingest-review-content"
+ >
+ <IngestReviewToolbar
+ files={files}
+ activeIndex={activeIndex}
+ activeFilename={activeFilename}
+ parsePreview={parsePreview}
+ showChunks={showChunks}
+ chunkSearch={chunkSearch}
+ onSelectFile={(index) => {
+ const file = files[index];
+ if (file) setSelectedKey(fileSelectionKey(file));
+ }}
+ onChunkSearch={setChunkSearch}
+ onClearChunkSearch={() => setChunkSearch("")}
+ />
+
+ {demo && (
+ <p
+ className="mt-3 text-xs text-muted-foreground"
+ data-testid="ingest-review-demo-banner"
+ >
+ Sample walkthrough — this document is not uploaded or indexed.
+ </p>
+ )}
+
+ <div
+ className={cn(
+ "mt-4 grid min-h-0 gap-4 lg:grid-cols-2",
+ expanded ? "flex-1" : "mb-0",
+ )}
+ >
+ <IngestReviewDocumentColumn
+ failed={failed}
+ failureMessage={failureMessage}
+ parsePreview={parsePreview}
+ highlightItemRefs={highlightItemRefs}
+ fallbackPage={fallbackPage}
+ highlightText={chunkHighlight?.text}
+ chunkLabel={chunkLabel}
+ hasChunks={chunkCount > 0}
+ expanded={expanded}
+ waitingForDocument={waitingForDocument}
+ onRetryPreview={retryParsePreview}
+ />
+ <IndexPane
+ steps={steps}
+ filename={activeFilename}
+ showIndexingPipeline={settings.showIndexingPipeline}
+ showChunkBoundaries={showChunks}
+ showChunkContents={settings.showChunkContents}
+ failed={failed}
+ failedStepIndex={failedStepIndex}
+ failureMessage={failureMessage}
+ awaitingChunks={chunkCount === 0 && !failed}
+ selectedChunkIndex={chunkHighlight?.index ?? null}
+ onSelectChunk={(chunk) => {
+ setChunkHighlight((prev) =>
+ prev?.index === chunk.index ? null : chunk,
+ );
+ }}
+ chunkSearch={chunkSearch}
+ onChunkSearchChange={setChunkSearch}
+ demoChunks={demo && chunkCount > 0 ? SAMPLE_DEMO_CHUNKS : undefined}
+ expanded={expanded}
+ onViewError={
+ activeTaskId ? () => onViewError?.(activeTaskId) : undefined
+ }
+ />
+ </div>
+
+ {showAutoOpenFooter && (
+ <IngestReviewAutoOpenFooter
+ autoOpen={settings.autoOpen}
+ onAutoOpenChange={(autoOpen) => updateSettings({ autoOpen })}
+ />
+ )}
+ </div>
+ );
+}
+
+// --- Dialog wrapper ----------------------------------------------------------
+
+export interface IngestReviewDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ taskIds?: string[];
+ previewFiles?: File[];
+ /** Client-only walkthrough — no upload or indexing. */
+ demo?: boolean;
+ /** Prefer these prefs (e.g. unsaved settings draft) over localStorage. */
+ settingsOverride?: IngestPreviewSettings;
+ /** Show the auto-open preference footer (onboarding only). */
+ showAutoOpenFooter?: boolean;
+}
+
+export function IngestReviewDialog({
+ open,
+ onOpenChange,
+ taskIds = [],
+ previewFiles = [],
+ demo = false,
+ settingsOverride,
+ showAutoOpenFooter = false,
+}: IngestReviewDialogProps) {
+ const { openTaskDialog } = useTask();
+ const [expanded, setExpanded] = useState(false);
+ const [wasOpen, setWasOpen] = useState(open);
+
+ // Reset expand state when the dialog re-opens (sync during render).
+ if (open !== wasOpen) {
+ setWasOpen(open);
+ if (open) {
+ setExpanded(false);
+ }
+ }
+
+ // Skip mounting while closed so preview polls don't run in the background.
+ if (!open || (taskIds.length === 0 && previewFiles.length === 0 && !demo)) {
+ return null;
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ className={cn(
+ "flex flex-col gap-3 p-4",
+ expanded
+ ? "h-[95vh] max-w-[95vw] overflow-hidden"
+ : "max-h-[90vh] max-w-5xl overflow-y-auto",
+ )}
+ data-testid="ingest-review-dialog"
+ >
+ <button
+ type="button"
+ onClick={() => setExpanded((prev) => !prev)}
+ aria-label={expanded ? "Shrink review" : "Expand review"}
+ className="absolute right-11 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
+ >
+ {expanded ? (
+ <Minimize2 className="h-4 w-4" />
+ ) : (
+ <Maximize2 className="h-4 w-4" />
+ )}
+ </button>
+ <DialogHeader className="shrink-0">
+ <DialogTitle>
+ {demo ? "Ingestion review (sample)" : "Ingestion review"}
+ </DialogTitle>
+ <DialogDescription className="sr-only">
+ {demo
+ ? "Sample walkthrough of how a document is parsed and indexed. Nothing is uploaded."
+ : "Review how this document is parsed and indexed."}
+ </DialogDescription>
+ </DialogHeader>
+ <IngestReviewContent
+ taskIds={taskIds}
+ previewFiles={previewFiles}
+ demo={demo}
+ settingsOverride={settingsOverride}
+ showAutoOpenFooter={showAutoOpenFooter}
+ expanded={expanded}
+ onViewError={(id) => {
+ onOpenChange(false);
+ openTaskDialog(id);
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/components/knowledge-dropdown.tsx b/frontend/components/knowledge-dropdown.tsx
index 6264a7d51..e90ccf6c9 100644
--- a/frontend/components/knowledge-dropdown.tsx
+++ b/frontend/components/knowledge-dropdown.tsx
@@ -15,6 +15,7 @@ import { toast } from "sonner";
import type { File as SearchFile } from "@/app/api/queries/useGetSearchQuery";
import { useGetTasksQuery } from "@/app/api/queries/useGetTasksQuery";
import { DuplicateHandlingDialog } from "@/components/duplicate-handling-dialog";
+import { IngestReviewDialog } from "@/components/ingest-review";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -31,8 +32,10 @@ import {
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { useTask } from "@/contexts/task-context";
+import { shouldAutoOpenIngestPreview } from "@/hooks/use-ingest-preview-settings";
import { usePermissions } from "@/hooks/use-permissions";
import { useSupportedFileTypes } from "@/hooks/use-supported-file-types";
import {
@@ -44,6 +47,11 @@ import {
getConnectorDescriptor,
getConnectorDescriptors,
} from "@/lib/connectors/registry";
+import {
+ EMPTY_PREVIEW,
+ isIngestPreviewEnabled,
+ type PreviewDialogState,
+} from "@/lib/ingest-preview";
import {
duplicateCheck,
uploadFiles,
@@ -91,6 +99,7 @@ const FolderIconWithColor = ({ className }: { className?: string }) => (
);
export function KnowledgeDropdown() {
+ const { runMode } = useAuth();
const { supportedExtensions, supportedExtensionSet } =
useSupportedFileTypes();
const { can } = usePermissions();
@@ -100,6 +109,9 @@ export function KnowledgeDropdown() {
const { refetch: refetchTasks } = useGetTasksQuery();
const queryClient = useQueryClient();
const router = useRouter();
+ const ingestPreviewEnabled = isIngestPreviewEnabled(runMode, {
+ isCloudBrand,
+ });
const [mounted, setMounted] = useState(false);
const [isMenuOpen, setIsMenuOpen] = useState(false);
const [showFolderDialog, setShowFolderDialog] = useState(false);
@@ -117,6 +129,7 @@ export function KnowledgeDropdown() {
>({});
const [pendingFile, setPendingFile] = useState<File | null>(null);
const [duplicateFilename, setDuplicateFilename] = useState<string>("");
+ const [preview, setPreview] = useState<PreviewDialogState>(EMPTY_PREVIEW);
const [pendingFolderUpload, setPendingFolderUpload] = useState<{
allFiles: File[];
nonDuplicateFiles: File[];
@@ -320,8 +333,54 @@ export function KnowledgeDropdown() {
resetFileInput();
};
+ const openPreviewForFiles = (files: File[], label: string) => {
+ if (!(ingestPreviewEnabled && shouldAutoOpenIngestPreview())) {
+ return;
+ }
+ setPreview({
+ open: true,
+ taskIds: [],
+ filename: label,
+ files,
+ });
+ };
+
+ /**
+ * Bind upload task IDs into the review dialog.
+ *
+ * Previously this always spread `prev` and only set `taskIds`. When Knowledge
+ * auto-open is off, `openPreviewForFiles` never runs, so `prev.open` stays
+ * false and the dialog kept a taskId while remaining invisible.
+ *
+ * Rules:
+ * - Dialog already open → attach taskIds (normal auto-open path).
+ * - Dialog closed but auto-open is on → open now with files (recovers a
+ * missed optimistic open).
+ * - Dialog closed and auto-open is off → leave closed; tasks stay in the tray.
+ */
+ const attachPreviewTaskIds = (
+ taskIds: string[],
+ fallback?: { files: File[]; filename: string },
+ ) => {
+ setPreview((prev) => {
+ if (prev.open) {
+ return { ...prev, open: true, taskIds };
+ }
+ if (shouldAutoOpenIngestPreview() && fallback) {
+ return {
+ open: true,
+ taskIds,
+ filename: fallback.filename,
+ files: fallback.files,
+ };
+ }
+ return prev;
+ });
+ };
+
const uploadFile = async (file: File, replace: boolean) => {
setFileUploading(true);
+ openPreviewForFiles([file], file.name);
trackStartProcess({
processType: "Ingestion",
process: "Document Upload",
@@ -331,8 +390,26 @@ export function KnowledgeDropdown() {
});
try {
- await uploadFileUtil(file, replace);
+ const result = await uploadFileUtil(
+ file,
+ replace,
+ false,
+ undefined,
+ ingestPreviewEnabled,
+ );
refetchTasks();
+ if (result.taskId) {
+ // Always track in the task tray; preview dialog is optional (auto-open).
+ addTask(result.taskId, { source: "file" });
+ if (result.previewMode) {
+ attachPreviewTaskIds([result.taskId as string], {
+ files: [file],
+ filename: file.name,
+ });
+ } else {
+ setPreview(EMPTY_PREVIEW);
+ }
+ }
} catch (error) {
trackProcessFailure({
processType: "Ingestion",
@@ -353,6 +430,7 @@ export function KnowledgeDropdown() {
toast.error("Upload failed", {
description: error instanceof Error ? error.message : "Unknown error",
});
+ setPreview(EMPTY_PREVIEW);
} finally {
setFileUploading(false);
}
@@ -370,31 +448,85 @@ export function KnowledgeDropdown() {
total_files: filesToUpload.length,
});
+ openPreviewForFiles(filesToUpload, `${filesToUpload.length} files`);
+
const batches: File[][] = [];
for (let i = 0; i < filesToUpload.length; i += uploadBatchSize) {
batches.push(filesToUpload.slice(i, i + uploadBatchSize));
}
- for (const batch of batches) {
- try {
- const result = await uploadFiles(batch, replace);
- addTask(result.taskId, { source: "folder" });
- } catch (error) {
- trackProcessFailure({
- processType: "Ingestion",
- process: "Document Upload",
- category: "Knowledge",
- source: "folder",
- resultValue: error instanceof Error ? error.message : "Unknown error",
- });
- console.error("[Folder Upload] Batch upload failed:", error);
- toast.error("Batch upload failed", {
- description: error instanceof Error ? error.message : "Unknown error",
- });
+ const taskIdsByBatch: (string | undefined)[] = [];
+ const failedBatchIndexes: number[] = [];
+ // Cap parallel batch uploads so large folders don't open every request at once.
+ const batchConcurrency = Math.min(2, batches.length);
+ let nextBatchIndex = 0;
+ // Set by any worker that gets previewMode=true; checked once after all
+ // batches finish so a concurrent false cannot close a successful open.
+ let previewModeConfirmed = false;
+
+ const runNextBatch = async () => {
+ while (nextBatchIndex < batches.length) {
+ const batchIndex = nextBatchIndex;
+ nextBatchIndex += 1;
+ const batch = batches[batchIndex];
+ if (!batch) continue;
+
+ try {
+ const result = await uploadFiles(
+ batch,
+ replace,
+ ingestPreviewEnabled,
+ );
+ addTask(result.taskId, { source: "folder" });
+ if (result.previewMode) {
+ previewModeConfirmed = true;
+ taskIdsByBatch[batchIndex] = result.taskId;
+ attachPreviewTaskIds(
+ taskIdsByBatch.filter((id): id is string => id !== undefined),
+ {
+ files: filesToUpload,
+ filename: `${filesToUpload.length} files`,
+ },
+ );
+ refetchTasks();
+ }
+ } catch (error) {
+ failedBatchIndexes.push(batchIndex);
+ trackProcessFailure({
+ processType: "Ingestion",
+ process: "Document Upload",
+ category: "Knowledge",
+ source: "folder",
+ resultValue:
+ error instanceof Error ? error.message : "Unknown error",
+ });
+ console.error("[Folder Upload] Batch upload failed:", error);
+ toast.error("Batch upload failed", {
+ description:
+ error instanceof Error ? error.message : "Unknown error",
+ });
+ }
}
+ };
+
+ await Promise.all(
+ Array.from({ length: batchConcurrency }, () => runNextBatch()),
+ );
+
+ // Close the optimistic open only after all workers finish. Doing this
+ // inside a worker races: a late previewMode=false can wipe a sibling's
+ // successful open between awaits.
+ if (!previewModeConfirmed) {
+ setPreview(EMPTY_PREVIEW);
}
refetchTasks();
+
+ if (failedBatchIndexes.length > 0) {
+ throw new Error(
+ `${failedBatchIndexes.length} of ${batches.length} batch upload(s) failed`,
+ );
+ }
};
const handleOverwriteFile = async () => {
@@ -402,12 +534,20 @@ export function KnowledgeDropdown() {
isFolderOverwriteConfirmedRef.current = true;
const { allFiles, duplicateNames, unsupportedCount } =
pendingFolderUpload;
- await uploadFolderBatches(allFiles, true);
- const unsupportedMessage =
- unsupportedCount > 0 ? `, skipped ${unsupportedCount} unsupported` : "";
- toast.success(
- `Processed ${allFiles.length} file(s), including ${duplicateNames.length} overwrite(s)${unsupportedMessage}`,
- );
+ try {
+ await uploadFolderBatches(allFiles, true);
+ const unsupportedMessage =
+ unsupportedCount > 0
+ ? `, skipped ${unsupportedCount} unsupported`
+ : "";
+ toast.success(
+ `Processed ${allFiles.length} file(s), including ${duplicateNames.length} overwrite(s)${unsupportedMessage}`,
+ );
+ } catch (error) {
+ toast.error("Folder upload incomplete", {
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
resetDuplicateDialogState();
return;
}
@@ -448,19 +588,26 @@ export function KnowledgeDropdown() {
const { nonDuplicateFiles, duplicateNames, unsupportedCount } =
pendingFolderUpload;
if (nonDuplicateFiles.length > 0) {
- await uploadFolderBatches(nonDuplicateFiles, false);
- const extraParts: string[] = [];
- if (duplicateNames.length > 0) {
- extraParts.push(`skipped ${duplicateNames.length} duplicate(s)`);
- }
- if (unsupportedCount > 0) {
- extraParts.push(`skipped ${unsupportedCount} unsupported`);
+ try {
+ await uploadFolderBatches(nonDuplicateFiles, false);
+ const extraParts: string[] = [];
+ if (duplicateNames.length > 0) {
+ extraParts.push(`skipped ${duplicateNames.length} duplicate(s)`);
+ }
+ if (unsupportedCount > 0) {
+ extraParts.push(`skipped ${unsupportedCount} unsupported`);
+ }
+ const suffix =
+ extraParts.length > 0 ? `, ${extraParts.join(", ")}` : "";
+ toast.success(
+ `Processed ${nonDuplicateFiles.length} file(s)${suffix}`,
+ );
+ } catch (error) {
+ toast.error("Folder upload incomplete", {
+ description:
+ error instanceof Error ? error.message : "Unknown error",
+ });
}
- const suffix =
- extraParts.length > 0 ? `, ${extraParts.join(", ")}` : "";
- toast.success(
- `Processed ${nonDuplicateFiles.length} file(s)${suffix}`,
- );
} else {
toast.info(
"Skipped duplicate files. All selected files were duplicates, so nothing was uploaded.",
@@ -887,6 +1034,15 @@ export function KnowledgeDropdown() {
duplicateLabel={duplicateFilename}
duplicateNames={pendingFolderUpload?.duplicateNames}
/>
+
+ <IngestReviewDialog
+ open={preview.open}
+ onOpenChange={(open) =>
+ setPreview((prev) => (open ? { ...prev, open } : EMPTY_PREVIEW))
+ }
+ taskIds={preview.taskIds}
+ previewFiles={preview.files}
+ />
</>
);
}
diff --git a/frontend/components/knowledge-search-input.tsx b/frontend/components/knowledge-search-input.tsx
index 9cb7f8857..f7972ba55 100644
--- a/frontend/components/knowledge-search-input.tsx
+++ b/frontend/components/knowledge-search-input.tsx
@@ -1,12 +1,45 @@
import { ArrowRight, Search, X } from "lucide-react";
-import { type ChangeEvent, type FormEvent, useCallback, useState } from "react";
+import { type ChangeEvent, type FormEvent, useState } from "react";
import { Button } from "@/components/ui/button";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { trackButton } from "@/lib/analytics";
import { cn } from "@/lib/utils";
import { filterAccentClasses } from "./knowledge-filter-panel";
-export const KnowledgeSearchInput = () => {
+export type KnowledgeSearchInputProps = {
+ /** Controlled value — when set with onSearch, skips global queryOverride. */
+ value?: string;
+ onSearch?: (query: string) => void;
+ onClear?: () => void;
+ placeholder?: string;
+ /** Hide the selected-filter chip (file-scoped panels). */
+ hideFilterChip?: boolean;
+ /** Hide the submit arrow (live-filter / header search). */
+ hideSubmit?: boolean;
+ className?: string;
+ inputClassName?: string;
+};
+
+function trackSearch(queryLength: number, hasFilter: boolean) {
+ trackButton({
+ CTA: "Search Knowledge",
+ elementId: "search-knowledge-button",
+ namespace: "knowledge",
+ payload: { queryLength, hasFilter },
+ });
+}
+
+export function KnowledgeSearchInput({
+ value,
+ onSearch,
+ onClear,
+ placeholder = "Search your documents...",
+ hideFilterChip = false,
+ hideSubmit = false,
+ className,
+ inputClassName,
+}: KnowledgeSearchInputProps = {}) {
+ const controlled = onSearch != null;
const {
selectedFilter,
setSelectedFilter,
@@ -15,45 +48,66 @@ export const KnowledgeSearchInput = () => {
setQueryOverride,
} = useKnowledgeFilter();
- const [searchQueryInput, setSearchQueryInput] = useState(queryOverride || "");
- const [prevQueryOverride, setPrevQueryOverride] = useState(queryOverride);
- if (queryOverride !== prevQueryOverride) {
- setPrevQueryOverride(queryOverride);
- setSearchQueryInput(queryOverride);
+ // Uncontrolled (knowledge page): draft until submit; sync when override changes.
+ const [draft, setDraft] = useState(queryOverride || "");
+ const [prevOverride, setPrevOverride] = useState(queryOverride);
+ if (!controlled && queryOverride !== prevOverride) {
+ setPrevOverride(queryOverride);
+ setDraft(queryOverride || "");
}
- const handleSearch = useCallback(
- (e?: FormEvent<HTMLFormElement>) => {
- if (e) e.preventDefault();
- trackButton({
- CTA: "Search Knowledge",
- elementId: "search-knowledge-button",
- namespace: "knowledge",
- payload: {
- queryLength: searchQueryInput.trim().length,
- hasFilter: !!selectedFilter,
- },
- });
- setQueryOverride(searchQueryInput.trim());
- },
- [searchQueryInput, setQueryOverride, selectedFilter],
- );
+ const inputValue = controlled ? (value ?? "") : draft;
+
+ const commitSearch = (raw: string) => {
+ const next = raw.trim();
+ trackSearch(next.length, Boolean(selectedFilter));
+ if (controlled) {
+ onSearch(next);
+ } else {
+ setQueryOverride(next);
+ }
+ };
+
+ const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ commitSearch(inputValue);
+ };
+
+ const handleClear = () => {
+ if (controlled) {
+ onClear?.();
+ onSearch("");
+ } else {
+ setDraft("");
+ setQueryOverride("");
+ }
+ };
+
+ const showClear = Boolean(inputValue);
return (
<form
- className="flex flex-1 max-w-[min(640px,100%)] min-w-[100px]"
- onSubmit={handleSearch}
+ className={cn(
+ "flex flex-1 max-w-[min(640px,100%)] min-w-[100px]",
+ className,
+ )}
+ onSubmit={handleSubmit}
>
- <div className="primary-input group/input min-h-10 !flex items-center flex-nowrap focus-within:border-foreground transition-colors !p-[0.3rem]">
- {selectedFilter?.name && (
+ <div
+ className={cn(
+ "primary-input group/input min-h-10 !flex w-full items-center flex-nowrap focus-within:border-foreground transition-colors !p-[0.3rem]",
+ inputClassName,
+ )}
+ >
+ {!hideFilterChip && selectedFilter?.name && (
<div
- title={selectedFilter?.name}
+ title={selectedFilter.name}
className={`flex items-center gap-1 h-full px-1.5 py-0.5 mr-1 rounded max-w-[25%] ${
filterAccentClasses[parsedFilterData?.color || "zinc"]
}`}
>
<span className="truncate text-xs font-medium">
- {selectedFilter?.name}
+ {selectedFilter.name}
</span>
<X
aria-label="Remove filter"
@@ -71,36 +125,41 @@ export const KnowledgeSearchInput = () => {
name="search-query"
id="search-query"
type="text"
- placeholder="Search your documents..."
- value={searchQueryInput}
- onChange={(e: ChangeEvent<HTMLInputElement>) =>
- setSearchQueryInput(e.target.value)
- }
+ placeholder={placeholder}
+ value={inputValue}
+ onChange={(e: ChangeEvent<HTMLInputElement>) => {
+ const next = e.target.value;
+ if (controlled) {
+ // File-scoped panels filter as you type / paste.
+ onSearch(next);
+ } else {
+ setDraft(next);
+ }
+ }}
/>
- {queryOverride && (
+ {showClear && (
<Button
variant="ghost"
className="h-full rounded-sm !px-1.5 !py-0"
type="button"
- onClick={() => {
- setSearchQueryInput("");
- setQueryOverride("");
- }}
+ onClick={handleClear}
>
<X className="h-4 w-4" />
</Button>
)}
- <Button
- variant="ghost"
- className={cn(
- "h-full rounded-sm !px-1.5 !py-0 hidden group-focus-within/input:block",
- searchQueryInput && "block",
- )}
- type="submit"
- >
- <ArrowRight className="h-4 w-4" />
- </Button>
+ {!hideSubmit && (
+ <Button
+ variant="ghost"
+ className={cn(
+ "h-full rounded-sm !px-1.5 !py-0 hidden group-focus-within/input:block",
+ inputValue && "block",
+ )}
+ type="submit"
+ >
+ <ArrowRight className="h-4 w-4" />
+ </Button>
+ )}
</div>
</form>
);
-};
+}
diff --git a/frontend/hooks/use-ingest-preview-settings.ts b/frontend/hooks/use-ingest-preview-settings.ts
new file mode 100644
index 000000000..d8a4ae907
--- /dev/null
+++ b/frontend/hooks/use-ingest-preview-settings.ts
@@ -0,0 +1,133 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+export type IngestPreviewAutoOpen = "every" | "never";
+
+export interface IngestPreviewSettings {
+ /** When the review opens automatically after a Knowledge ingest starts. */
+ autoOpen: IngestPreviewAutoOpen;
+ /** Show the per-chunk breakdown (the chunk cards). */
+ showChunkBoundaries: boolean;
+ /** Show the reading/chunking/embedding/stored pipeline steps. */
+ showIndexingPipeline: boolean;
+ /** Show each chunk's extracted text (vs. metadata only). */
+ showChunkContents: boolean;
+ /** Toast when ingestion finishes while the review is open. */
+ completionNotification: boolean;
+}
+
+export const DEFAULT_INGEST_PREVIEW_SETTINGS: IngestPreviewSettings = {
+ autoOpen: "never",
+ showChunkBoundaries: true,
+ showIndexingPipeline: true,
+ showChunkContents: true,
+ completionNotification: true,
+};
+
+const SETTINGS_KEY = "openrag.ingest-preview.settings";
+
+export const INGEST_PREVIEW_AUTO_OPEN_OPTIONS: ReadonlyArray<{
+ value: IngestPreviewAutoOpen;
+ label: string;
+ description: string;
+}> = [
+ {
+ value: "every",
+ label: "Every upload",
+ description: "Open the review automatically when a document is ingested.",
+ },
+ {
+ value: "never",
+ label: "Never",
+ description: "Never open the preview.",
+ },
+];
+
+/** Map legacy localStorage values to the current two-option set. */
+function normalizeAutoOpen(value: unknown): IngestPreviewAutoOpen | null {
+ if (value === "every" || value === "never") return value;
+ // Former "Onboarding only" — same Knowledge behavior as Never.
+ if (value === "first-run") return "never";
+ return null;
+}
+
+/** Read persisted settings, falling back to defaults for any missing/invalid field. */
+export function readIngestPreviewSettings(): IngestPreviewSettings {
+ if (typeof window === "undefined") {
+ return DEFAULT_INGEST_PREVIEW_SETTINGS;
+ }
+ try {
+ const raw = window.localStorage.getItem(SETTINGS_KEY);
+ if (!raw) return DEFAULT_INGEST_PREVIEW_SETTINGS;
+ const parsed: unknown = JSON.parse(raw);
+ if (
+ parsed === null ||
+ typeof parsed !== "object" ||
+ Array.isArray(parsed)
+ ) {
+ return DEFAULT_INGEST_PREVIEW_SETTINGS;
+ }
+ const settings = parsed as Partial<IngestPreviewSettings>;
+ return {
+ autoOpen:
+ normalizeAutoOpen(settings.autoOpen) ??
+ DEFAULT_INGEST_PREVIEW_SETTINGS.autoOpen,
+ showChunkBoundaries:
+ typeof settings.showChunkBoundaries === "boolean"
+ ? settings.showChunkBoundaries
+ : DEFAULT_INGEST_PREVIEW_SETTINGS.showChunkBoundaries,
+ showIndexingPipeline:
+ typeof settings.showIndexingPipeline === "boolean"
+ ? settings.showIndexingPipeline
+ : DEFAULT_INGEST_PREVIEW_SETTINGS.showIndexingPipeline,
+ showChunkContents:
+ typeof settings.showChunkContents === "boolean"
+ ? settings.showChunkContents
+ : DEFAULT_INGEST_PREVIEW_SETTINGS.showChunkContents,
+ completionNotification:
+ typeof settings.completionNotification === "boolean"
+ ? settings.completionNotification
+ : DEFAULT_INGEST_PREVIEW_SETTINGS.completionNotification,
+ };
+ } catch {
+ return DEFAULT_INGEST_PREVIEW_SETTINGS;
+ }
+}
+
+function writeIngestPreviewSettings(settings: IngestPreviewSettings): void {
+ if (typeof window === "undefined") return;
+ window.localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
+}
+
+/**
+ * Whether Knowledge uploads should auto-open the review.
+ * Onboarding always opens when the feature flag is on (ignores this).
+ * `never` → Knowledge does not auto-open.
+ */
+export function shouldAutoOpenIngestPreview(
+ settings: IngestPreviewSettings = readIngestPreviewSettings(),
+): boolean {
+ return settings.autoOpen === "every";
+}
+
+/** Stateful accessor for the settings form; persists on every change. */
+export function useIngestPreviewSettings() {
+ const [settings, setSettings] = useState<IngestPreviewSettings>(
+ DEFAULT_INGEST_PREVIEW_SETTINGS,
+ );
+
+ useEffect(() => {
+ setSettings(readIngestPreviewSettings());
+ }, []);
+
+ const updateSettings = (patch: Partial<IngestPreviewSettings>) => {
+ setSettings((prev) => {
+ const next = { ...prev, ...patch };
+ writeIngestPreviewSettings(next);
+ return next;
+ });
+ };
+
+ return { settings, updateSettings };
+}
diff --git a/frontend/lib/file-chunks.ts b/frontend/lib/file-chunks.ts
new file mode 100644
index 000000000..3cbaee257
--- /dev/null
+++ b/frontend/lib/file-chunks.ts
@@ -0,0 +1,19 @@
+import type { ParsedQueryData } from "@/contexts/knowledge-filter-context";
+import { SEARCH_CONSTANTS } from "@/lib/constants";
+
+/** Query data that loads all chunks for one filename (OpenSearch data_sources). */
+export function fileScopedSearchQueryData(filename: string): ParsedQueryData {
+ return {
+ query: "*",
+ filters: {
+ data_sources: [filename],
+ document_types: [],
+ owners: [],
+ connector_types: [],
+ },
+ limit: SEARCH_CONSTANTS.WILDCARD_QUERY_LIMIT,
+ scoreThreshold: 0,
+ color: "zinc",
+ icon: "folder",
+ };
+}
diff --git a/frontend/lib/ingest-preview-demo.ts b/frontend/lib/ingest-preview-demo.ts
new file mode 100644
index 000000000..00384ebd4
--- /dev/null
+++ b/frontend/lib/ingest-preview-demo.ts
@@ -0,0 +1,67 @@
+import type { IndexProofChunk } from "@/app/api/queries/useIngestPreviewQuery";
+
+export const SAMPLE_DEMO_FILENAME = "openrag-ingest-preview-sample.txt";
+
+const SAMPLE_TITLE = "OpenRAG ingest preview sample";
+
+const SAMPLE_INTRO = `This short document demonstrates how files are parsed and
+chunked before they are used for retrieval. Nothing from this
+sample is saved to your knowledge base.`;
+
+const SAMPLE_STEPS = [
+ "Reading layout",
+ "Creating chunks",
+ "Generating embeddings",
+ "Storing in OpenSearch",
+] as const;
+
+/** Local sample file for the settings try-out (never uploaded). */
+export function createSampleDemoFile(): File {
+ const body = [
+ SAMPLE_TITLE,
+ "",
+ SAMPLE_INTRO,
+ "",
+ ...SAMPLE_STEPS.map((step) => `- ${step}`),
+ "",
+ ].join("\n");
+ return new File([body], SAMPLE_DEMO_FILENAME, { type: "text/plain" });
+}
+
+/**
+ * Minimal DoclingDocument so DoclingTextPreview can render the sample with the
+ * same annotation chrome as a real non-PDF parse.
+ */
+export function buildSampleDemoDocument(): Record<string, unknown> {
+ const texts = [
+ { label: "title", text: SAMPLE_TITLE },
+ { label: "text", text: SAMPLE_INTRO },
+ ...SAMPLE_STEPS.map((step) => ({ label: "list_item", text: step })),
+ ];
+ return {
+ body: texts.map((_, index) => ({ $ref: `#/texts/${index}` })),
+ texts,
+ };
+}
+
+export const SAMPLE_DEMO_STATS = {
+ page_count: 1,
+ text_count: 2 + SAMPLE_STEPS.length,
+ table_count: 0,
+ picture_count: 0,
+};
+
+export const SAMPLE_DEMO_CHUNKS: IndexProofChunk[] = [
+ {
+ chunk_id: "demo-chunk-1",
+ page: 1,
+ text_preview: `${SAMPLE_TITLE}\n\n${SAMPLE_INTRO}`,
+ char_count: SAMPLE_TITLE.length + SAMPLE_INTRO.length + 2,
+ },
+ {
+ chunk_id: "demo-chunk-2",
+ page: 1,
+ text_preview: SAMPLE_STEPS.map((step) => `• ${step}`).join("\n"),
+ char_count: SAMPLE_STEPS.map((step) => `• ${step}`).join("\n").length,
+ },
+];
diff --git a/frontend/lib/ingest-preview.ts b/frontend/lib/ingest-preview.ts
new file mode 100644
index 000000000..079da9e23
--- /dev/null
+++ b/frontend/lib/ingest-preview.ts
@@ -0,0 +1,261 @@
+/** Ingest preview helpers (run-mode UI gate; backend also requires the env flag). */
+
+import { IBM_THEME_DEV } from "@/lib/brand";
+
+/**
+ * Eligible run modes for showing ingest-preview UI.
+ * SaaS omitted until product approval — add "saas" here to restore.
+ * The backend still requires `OPENRAG_INGEST_PREVIEW_ENABLED=true` before
+ * `preview_mode` is honored — uploads then report `preview_mode` in the 202 body.
+ */
+const INGEST_PREVIEW_RUN_MODES = new Set(["oss"]);
+
+/**
+ * Client-side gate for showing ingest-preview UI.
+ * Currently OSS only; SaaS deferred pending product approval.
+ *
+ * Local IBM theme (`NEXT_PUBLIC_IBM_THEME_DEV`): the header OSS/IBM switch does
+ * not change backend `runMode`, so pass `isCloudBrand` to hide preview in the
+ * IBM/SaaS brand view the same way real `OPENRAG_RUN_MODE=saas` would.
+ */
+export function isIngestPreviewEnabled(
+ runMode: string | null | undefined,
+ options?: { isCloudBrand?: boolean },
+): boolean {
+ if (runMode == null || !INGEST_PREVIEW_RUN_MODES.has(runMode)) {
+ return false;
+ }
+ if (IBM_THEME_DEV && options?.isCloudBrand) {
+ return false;
+ }
+ return true;
+}
+
+export type ChunkPageNumbering = "zero-based" | "one-based";
+
+/** One pass over chunks: distinct page count + Docling page numbering. */
+export function summarizeChunkPages(
+ chunks: ReadonlyArray<{ page?: number | null }>,
+): { pageCount: number; numbering: ChunkPageNumbering } {
+ const pages = new Set<number>();
+ let minPage: number | undefined;
+ for (const chunk of chunks) {
+ const page = chunk.page;
+ if (typeof page !== "number") continue;
+ pages.add(page);
+ if (minPage === undefined || page < minPage) {
+ minPage = page;
+ }
+ }
+ return {
+ pageCount: pages.size,
+ numbering: minPage === 0 ? "zero-based" : "one-based",
+ };
+}
+
+function pageHasEmbeddedImage(page: unknown): boolean {
+ const image = (page as { image?: unknown } | null)?.image;
+ if (!image) return false;
+ if (typeof image === "string") return image.length > 0;
+ const { uri, data } = image as { uri?: unknown; data?: unknown };
+ return Boolean(uri) || Boolean(data);
+}
+
+/**
+ * Whether the Docling JSON embeds full-page renderings. Only PDFs and image
+ * inputs produce these; office formats parse to structured items without page
+ * rasters, so `docling-img` would render blank for them.
+ */
+export function doclingHasPageImages(
+ document: Record<string, unknown>,
+): boolean {
+ const pages = (document as { pages?: unknown }).pages;
+ if (!pages) return false;
+ if (Array.isArray(pages)) {
+ for (const page of pages) {
+ if (pageHasEmbeddedImage(page)) return true;
+ }
+ return false;
+ }
+ for (const key of Object.keys(pages as object)) {
+ if (pageHasEmbeddedImage((pages as Record<string, unknown>)[key])) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/** Shared state shape for ingest-review dialog open from Knowledge / onboarding. */
+export type PreviewDialogState = {
+ open: boolean;
+ taskIds: string[];
+ filename: string;
+ files: File[];
+};
+
+export const EMPTY_PREVIEW: PreviewDialogState = {
+ open: false,
+ taskIds: [],
+ filename: "",
+ files: [],
+};
+
+type DoclingProv = { page_no?: number };
+
+type MatchableDoclingItem = {
+ self_ref?: string;
+ text?: string;
+ orig?: string;
+ prov?: DoclingProv[];
+ data?: { grid?: Array<Array<{ text?: string }>> };
+};
+
+function normalizeMatchText(value: string): string {
+ return value.toLowerCase().replace(/\s+/g, " ").trim();
+}
+
+function itemPlainText(item: MatchableDoclingItem): string {
+ if (typeof item.text === "string" && item.text.trim()) {
+ return item.text;
+ }
+ // PDF/Docling items sometimes expose content on `orig` instead of `text`.
+ if (typeof item.orig === "string" && item.orig.trim()) {
+ return item.orig;
+ }
+ const grid = item.data?.grid;
+ if (!Array.isArray(grid)) return "";
+ return grid.flatMap((row) => row.map((cell) => cell?.text ?? "")).join(" ");
+}
+
+function itemPages(item: MatchableDoclingItem): number[] {
+ if (!Array.isArray(item.prov)) return [];
+ const pages: number[] = [];
+ for (const prov of item.prov) {
+ if (typeof prov.page_no === "number") pages.push(prov.page_no);
+ }
+ return pages;
+}
+
+function scoreTextOverlap(chunkText: string, itemText: string): number {
+ const chunk = normalizeMatchText(chunkText);
+ const item = normalizeMatchText(itemText);
+ if (!chunk || !item) return 0;
+ if (chunk.includes(item) || item.includes(chunk)) {
+ return (
+ Math.min(chunk.length, item.length) / Math.max(chunk.length, item.length)
+ );
+ }
+ const chunkTokens = new Set(chunk.split(" ").filter((t) => t.length > 2));
+ if (chunkTokens.size === 0) return 0;
+ let hits = 0;
+ for (const token of item.split(" ")) {
+ if (chunkTokens.has(token)) hits += 1;
+ }
+ return hits / chunkTokens.size;
+}
+
+const MIN_MATCH_SCORE = 0.2;
+
+export type ChunkDoclingMatch = {
+ /** Matched layout item refs (for text-preview emphasis / PDF itemPart). */
+ itemRefs: string[];
+ /** True when we fell back to the whole page. */
+ pageFallback: boolean;
+ /** Docling 1-based page for scroll/overlay (from match prov or chunk page). */
+ page?: number;
+};
+
+/**
+ * Map an indexed chunk to Docling layout item refs by text overlap.
+ * Chunk page is a hint only — indexed page metadata is often wrong/stale, so
+ * when nothing matches on that page we search the whole document.
+ */
+export function matchChunkToDoclingItems(
+ document: Record<string, unknown> | null | undefined,
+ chunk: { page?: number | null; text: string },
+ numbering: ChunkPageNumbering = "one-based",
+): ChunkDoclingMatch | null {
+ if (typeof chunk.page !== "number" && !chunk.text.trim()) {
+ return null;
+ }
+
+ const doclingPage =
+ typeof chunk.page === "number"
+ ? numbering === "zero-based"
+ ? chunk.page + 1
+ : chunk.page
+ : null;
+
+ const pageFallback =
+ doclingPage != null
+ ? {
+ itemRefs: [] as string[],
+ pageFallback: true,
+ page: doclingPage,
+ }
+ : null;
+
+ if (!document) return pageFallback;
+
+ type Candidate = { ref: string; score: number; page?: number };
+ const collections: Array<{ key: string; items: unknown }> = [
+ { key: "texts", items: document.texts },
+ { key: "tables", items: document.tables },
+ { key: "pictures", items: document.pictures },
+ ];
+
+ const collectCandidates = (restrictPage: number | null): Candidate[] => {
+ const candidates: Candidate[] = [];
+ for (const { key, items } of collections) {
+ if (!Array.isArray(items)) continue;
+ for (let i = 0; i < items.length; i += 1) {
+ const item = items[i] as MatchableDoclingItem;
+ const pages = itemPages(item);
+ if (
+ restrictPage != null &&
+ pages.length > 0 &&
+ !pages.includes(restrictPage)
+ ) {
+ continue;
+ }
+ const plain = itemPlainText(item);
+ const score = scoreTextOverlap(chunk.text, plain);
+ if (score < MIN_MATCH_SCORE) continue;
+ const ref =
+ typeof item.self_ref === "string" && item.self_ref.startsWith("#/")
+ ? item.self_ref
+ : `#/${key}/${i}`;
+ candidates.push({
+ ref,
+ score,
+ page: pages[0],
+ });
+ }
+ }
+ return candidates;
+ };
+
+ // Prefer same-page matches, then search all pages by text (page metadata
+ // on indexed chunks is frequently missing or stuck on page 1).
+ let candidates = collectCandidates(doclingPage);
+ if (candidates.length === 0) {
+ candidates = collectCandidates(null);
+ }
+
+ if (candidates.length === 0) return pageFallback;
+
+ candidates.sort((a, b) => b.score - a.score);
+ const top = candidates[0]?.score ?? 0;
+ const threshold = Math.max(MIN_MATCH_SCORE, top * 0.6);
+ const itemRefs: string[] = [];
+ for (const candidate of candidates) {
+ if (candidate.score < threshold) break;
+ itemRefs.push(candidate.ref);
+ if (itemRefs.length >= 8) break;
+ }
+ return {
+ itemRefs,
+ pageFallback: false,
+ page: candidates[0]?.page ?? doclingPage ?? undefined,
+ };
+}
diff --git a/frontend/lib/upload-utils.ts b/frontend/lib/upload-utils.ts
index 2793a43cc..e97920ad1 100644
--- a/frontend/lib/upload-utils.ts
+++ b/frontend/lib/upload-utils.ts
@@ -60,6 +60,8 @@ export interface UploadFileResult {
createFilter?: boolean;
filename?: string;
taskId?: string;
+ /** Whether the backend honored preview=true (flag + run-mode gated). */
+ previewMode?: boolean;
}
export async function duplicateCheck(
@@ -82,12 +84,16 @@ export async function duplicateCheck(
export async function uploadFiles(
files: File[],
replace = false,
-): Promise<{ taskId: string; fileCount: number }> {
+ preview = false,
+): Promise<{ taskId: string; fileCount: number; previewMode: boolean }> {
const formData = new FormData();
for (const file of files) {
formData.append("file", file);
}
formData.append("replace_duplicates", replace.toString());
+ if (preview) {
+ formData.append("preview", "true");
+ }
const uploadResponse = await fetch("/api/router/upload_ingest", {
method: "POST",
@@ -111,12 +117,15 @@ export async function uploadFiles(
const taskId = (json as { task_id?: string }).task_id;
const fileCount =
(json as { file_count?: number }).file_count ?? files.length;
+ const previewMode = Boolean(
+ (json as { preview_mode?: boolean }).preview_mode,
+ );
if (!taskId) {
throw new Error("Upload successful but no task ID returned");
}
- return { taskId, fileCount };
+ return { taskId, fileCount, previewMode };
}
export interface UploadFileCallbacks {
@@ -129,6 +138,7 @@ export async function uploadFile(
replace = false,
createFilter = false,
callbacks?: UploadFileCallbacks,
+ preview = false,
): Promise<UploadFileResult> {
try {
const formData = new FormData();
@@ -137,6 +147,9 @@ export async function uploadFile(
if (createFilter) {
formData.append("create_filter", "true");
}
+ if (preview) {
+ formData.append("preview", "true");
+ }
const uploadResponse = await fetch("/api/router/upload_ingest", {
method: "POST",
@@ -193,6 +206,9 @@ export async function uploadFile(
const shouldCreateFilter = (uploadIngestJson as { create_filter?: boolean })
.create_filter;
const filename = (uploadIngestJson as { filename?: string }).filename;
+ const previewMode = Boolean(
+ (uploadIngestJson as { preview_mode?: boolean }).preview_mode,
+ );
const result: UploadFileResult = {
fileId,
@@ -204,6 +220,7 @@ export async function uploadFile(
createFilter: shouldCreateFilter,
filename,
taskId,
+ previewMode,
};
return result;
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index bafc0cb32..ea3152bfe 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -8,9 +8,10 @@
"name": "frontend",
"version": "0.1.0",
"dependencies": {
+ "@docling/docling-components": "^0.0.7",
"@radix-ui/react-accordion": "^1.2.14",
"@radix-ui/react-avatar": "^1.2.0",
- "@radix-ui/react-checkbox": "^1.3.9",
+ "@radix-ui/react-checkbox": "^1.3.11",
"@radix-ui/react-collapsible": "^1.1.14",
"@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dropdown-menu": "^2.1.18",
@@ -281,13 +282,29 @@
"kuler": "^2.0.0"
}
},
+ "node_modules/@docling/docling-components": {
+ "version": "0.0.7",
+ "resolved": "https://registry.npmjs.org/@docling/docling-components/-/docling-components-0.0.7.tgz",
+ "integrity": "sha512-1dl3WVyLxZja1ffKAwk8ZXiKfZ4XTSZMA0QNzFab4OQWuemEpN3R2U0SqoSiC+PA19sc4Qi9tvaS4i2iXoop0g==",
+ "license": "MIT",
+ "dependencies": {
+ "@docling/docling-core": "^0.0.7",
+ "@lit/task": "^1.0.2",
+ "lit": "^3.3.0"
+ }
+ },
+ "node_modules/@docling/docling-core": {
+ "version": "0.0.7",
+ "resolved": "https://registry.npmjs.org/@docling/docling-core/-/docling-core-0.0.7.tgz",
+ "integrity": "sha512-5gobonNYuhX1SW7lBpldtRFsTGIGdpLC5tAQnvUAGWJdzmbS5D5nrUWF4GebbKP1f9P3AmK65Bqeu5bb36zP2A==",
+ "license": "MIT"
+ },
"node_modules/@emnapi/core": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
"integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.2",
"tslib": "^2.4.0"
@@ -299,7 +316,6 @@
"integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"tslib": "^2.4.0"
}
@@ -387,6 +403,30 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@lit-labs/ssr-dom-shim": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz",
+ "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@lit/reactive-element": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz",
+ "integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@lit-labs/ssr-dom-shim": "^1.5.0"
+ }
+ },
+ "node_modules/@lit/task": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@lit/task/-/task-1.0.3.tgz",
+ "integrity": "sha512-1gJGJl8WON+2j0y9xfcD+XsS1rvcy3XDgsIhcdUW++yTR8ESjZW6o7dn8M8a4SZM8NnJe6ynS2cKWwsbfLOurg==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@lit/reactive-element": "^1.0.0 || ^2.0.0"
+ }
+ },
"node_modules/@lukeed/csprng": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz",
@@ -1248,7 +1288,6 @@
"integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",
"devOptional": true,
"license": "Apache-2.0",
- "peer": true,
"dependencies": {
"playwright": "1.61.1"
},
@@ -1353,18 +1392,18 @@
}
},
"node_modules/@radix-ui/react-checkbox": {
- "version": "1.3.9",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.9.tgz",
- "integrity": "sha512-YPXZlqjrKVqKtVD2F828CApHwu+PEu30i7x0Y9gg6SbQ3fJbcaQlDkGPT0gW6HjxoCjAEt8uJ494F1S61KpIjQ==",
+ "version": "1.3.11",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.11.tgz",
+ "integrity": "sha512-Gnptr9pDDQxD3hgq2dtPbtrp/c2qH1mBwIzw3X/ivrMb2e1t0jMTi606fVEqFPaQR1ggXIVQWKj3P2WW9v7zGQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.7",
- "@radix-ui/react-compose-refs": "1.1.4",
- "@radix-ui/react-context": "1.2.1",
- "@radix-ui/react-presence": "1.1.9",
- "@radix-ui/react-primitive": "2.1.8",
- "@radix-ui/react-use-controllable-state": "1.2.5",
- "@radix-ui/react-use-size": "1.1.3"
+ "@radix-ui/react-compose-refs": "1.1.5",
+ "@radix-ui/react-context": "1.2.2",
+ "@radix-ui/react-presence": "1.1.10",
+ "@radix-ui/react-primitive": "2.1.10",
+ "@radix-ui/react-use-controllable-state": "1.2.6",
+ "@radix-ui/react-use-size": "1.1.4"
},
"peerDependencies": {
"@types/react": "*",
@@ -1388,9 +1427,9 @@
"license": "MIT"
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-compose-refs": {
- "version": "1.1.4",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.4.tgz",
- "integrity": "sha512-pWJo6lQAfR6uy1n7ii7PaCc9dLPwTXDYbQpORZU5B548Aqvl2pP1SM1vJGKyxIFqZMHRopRO4CQYX2iXAIB5jA==",
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz",
+ "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
@@ -1403,9 +1442,9 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-context": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.2.1.tgz",
- "integrity": "sha512-EraVbFjiIjibpLr6EjvEDmSCYJU2SlKDMiO+qEK/D9GOWnQoAQlpQo2occGYC1UM9MBeEx5Bek3UtW/Qi57vAg==",
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.2.2.tgz",
+ "integrity": "sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
@@ -1418,12 +1457,12 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-presence": {
- "version": "1.1.9",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.9.tgz",
- "integrity": "sha512-LTi1v05bprIb8/GSY/GWusI0jfsYjQ3CD3Nin8o7jVxnpHzVQfzjOQJoJTQkE9bdmOnsS7SFdhkXiBv8PrYnxw==",
+ "version": "1.1.10",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.10.tgz",
+ "integrity": "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw==",
"license": "MIT",
"dependencies": {
- "@radix-ui/react-use-layout-effect": "1.1.3"
+ "@radix-ui/react-use-layout-effect": "1.1.4"
},
"peerDependencies": {
"@types/react": "*",
@@ -1441,12 +1480,12 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-primitive": {
- "version": "2.1.8",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.8.tgz",
- "integrity": "sha512-DOlK1BdcIeYYUcFkSYFka4v1h95XTov93b0jCgW1EEiZuIhdwHY2NlE1teLIh+p0uBsuZI5A+voay+iVWpprfA==",
+ "version": "2.1.10",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.10.tgz",
+ "integrity": "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg==",
"license": "MIT",
"dependencies": {
- "@radix-ui/react-slot": "1.3.1"
+ "@radix-ui/react-slot": "1.3.3"
},
"peerDependencies": {
"@types/react": "*",
@@ -1464,13 +1503,12 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-slot": {
- "version": "1.3.1",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.3.1.tgz",
- "integrity": "sha512-Bu/aAQHFFh6/QAvXAeUMurJ9fbW0JUIqlojU/yBXZ7cAVqy75Y7JYYyuCr9zLNF0p4WWoJYV54CTUIf4l7FzTw==",
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.3.3.tgz",
+ "integrity": "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q==",
"license": "MIT",
"dependencies": {
- "@radix-ui/primitive": "1.1.7",
- "@radix-ui/react-compose-refs": "1.1.4"
+ "@radix-ui/react-compose-refs": "1.1.5"
},
"peerDependencies": {
"@types/react": "*",
@@ -1483,14 +1521,14 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-use-controllable-state": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.5.tgz",
- "integrity": "sha512-UB1dXpxvHjR48poyKdKdTm7jT0kp3elkUKdKQiOkirlbYumqXinSJtrjDsr9maXNPvL12bKI4CDSmydms/9Aeg==",
+ "version": "1.2.6",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.6.tgz",
+ "integrity": "sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.7",
- "@radix-ui/react-use-effect-event": "0.0.4",
- "@radix-ui/react-use-layout-effect": "1.1.3"
+ "@radix-ui/react-use-effect-event": "0.0.5",
+ "@radix-ui/react-use-layout-effect": "1.1.4"
},
"peerDependencies": {
"@types/react": "*",
@@ -1503,12 +1541,12 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-use-effect-event": {
- "version": "0.0.4",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.4.tgz",
- "integrity": "sha512-XYcfa6wlXDCwQtePuEiPmXLSAhGL4DWtedSyRgGbG3y10mw+OnrLp6SyeY1gJFMiYF0Dx0nMAX9InylKbLEFQQ==",
+ "version": "0.0.5",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz",
+ "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==",
"license": "MIT",
"dependencies": {
- "@radix-ui/react-use-layout-effect": "1.1.3"
+ "@radix-ui/react-use-layout-effect": "1.1.4"
},
"peerDependencies": {
"@types/react": "*",
@@ -1521,9 +1559,9 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-use-layout-effect": {
- "version": "1.1.3",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.3.tgz",
- "integrity": "sha512-rDiah9wvtqihWtWz02XreeRKIxt2EJF8y5D9rtY9l5A2zxePAtcPiOMpDugNRw5bFHz+1/8viVoc7ZVKiJknCw==",
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz",
+ "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
@@ -1536,12 +1574,12 @@
}
},
"node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-use-size": {
- "version": "1.1.3",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.3.tgz",
- "integrity": "sha512-jJq6tQQLvO/z4uWbztjwPV+1a/+H4rCaWypasLB/ac8DEdd6+p7dIm7o3F6P2KZPGkPMqD4s5424EdAdoU+GLA==",
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.4.tgz",
+ "integrity": "sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw==",
"license": "MIT",
"dependencies": {
- "@radix-ui/react-use-layout-effect": "1.1.3"
+ "@radix-ui/react-use-layout-effect": "1.1.4"
},
"peerDependencies": {
"@types/react": "*",
@@ -2667,7 +2705,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"license": "MIT",
- "peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -2678,7 +2715,6 @@
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"devOptional": true,
"license": "MIT",
- "peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -2698,6 +2734,12 @@
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==",
"license": "MIT"
},
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "license": "MIT"
+ },
"node_modules/@types/unist": {
"version": "2.0.11",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
@@ -2950,7 +2992,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.10.38",
"caniuse-lite": "^1.0.30001799",
@@ -4183,6 +4224,37 @@
"node": ">=22.13.0"
}
},
+ "node_modules/lit": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.3.tgz",
+ "integrity": "sha512-fycuvZg/hkpozL00lm1pEJH5nN/lr9ZXd6mJI2HSN4+Bzc+LDNdEApJ6HFbPkdFNHLvOplIIuJvxkS4XUxqirw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@lit/reactive-element": "^2.1.0",
+ "lit-element": "^4.2.0",
+ "lit-html": "^3.3.0"
+ }
+ },
+ "node_modules/lit-element": {
+ "version": "4.2.2",
+ "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz",
+ "integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@lit-labs/ssr-dom-shim": "^1.5.0",
+ "@lit/reactive-element": "^2.1.0",
+ "lit-html": "^3.3.0"
+ }
+ },
+ "node_modules/lit-html": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.3.tgz",
+ "integrity": "sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@types/trusted-types": "^2.0.2"
+ }
+ },
"node_modules/log-update": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz",
@@ -5650,7 +5722,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"nanoid": "^3.3.12",
"picocolors": "^1.1.1",
@@ -5842,7 +5913,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
"integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -5852,7 +5922,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
"integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -6556,7 +6625,6 @@
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",
"integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
diff --git a/frontend/package.json b/frontend/package.json
index 90b74328e..ca9a026dc 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -17,9 +17,10 @@
"prepare": "cd .. && npx husky frontend/.husky || true"
},
"dependencies": {
+ "@docling/docling-components": "^0.0.7",
"@radix-ui/react-accordion": "^1.2.14",
"@radix-ui/react-avatar": "^1.2.0",
- "@radix-ui/react-checkbox": "^1.3.9",
+ "@radix-ui/react-checkbox": "^1.3.11",
"@radix-ui/react-collapsible": "^1.1.14",
"@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dropdown-menu": "^2.1.18",
diff --git a/frontend/types/docling-components.d.ts b/frontend/types/docling-components.d.ts
new file mode 100644
index 000000000..a1b3eea56
--- /dev/null
+++ b/frontend/types/docling-components.d.ts
@@ -0,0 +1 @@
+declare module "@docling/docling-components";
diff --git a/src/api/connectors.py b/src/api/connectors.py
index 6f25e7573..812540daf 100644
--- a/src/api/connectors.py
+++ b/src/api/connectors.py
@@ -766,7 +766,8 @@ class ConnectorSyncBody(BaseModel):
# rather than failing. Set by the provider upload UI after the user confirms
# overwrite in the duplicate dialog.
replace_duplicates: bool = False
- # When True (OSS/SaaS), run the ingest in preview mode (same as direct upload).
+ # When True (OSS only for now; SaaS deferred), run the ingest in preview mode
+ # (same as direct upload). Honored only when is_ingest_preview_enabled().
preview: bool = False
# When True (COS only), index chunks without an owner field so OpenSearch DLS
# makes them visible to all users in the instance. Temporary CIO mechanism;
@@ -1267,8 +1268,9 @@ async def connector_sync(
selected_files = [f.get("id") for f in selected_files_raw if f.get("id")]
file_infos = selected_files_raw
- # Preview mode is opt-in from the connector upload UI (OSS/SaaS). It applies
- # to user-initiated ingests (explicit file selection), not automated re-sync.
+ # Preview mode is opt-in from the connector upload UI (OSS only for now;
+ # SaaS deferred pending product approval). It applies to user-initiated
+ # ingests (explicit file selection), not automated re-sync.
preview_mode = body.preview and is_ingest_preview_enabled()
try:
diff --git a/src/api/ingest_preview.py b/src/api/ingest_preview.py
index 4ad764481..ecaadf6ee 100644
--- a/src/api/ingest_preview.py
+++ b/src/api/ingest_preview.py
@@ -35,6 +35,39 @@ def _require_preview_task(task_service: Any, user: User, task_id: str):
return upload_task, None
+async def get_parse_preview(
+ task_id: str,
+ preview_service: Annotated[Any, Depends(get_ingest_preview_service)],
+ task_service: Annotated[Any, Depends(get_task_service)],
+ user: Annotated[User, Depends(require_permission("knowledge:upload"))],
+ file: str | None = None,
+):
+ """Return cached Docling JSON for a preview-mode ingest task.
+
+ ``file`` selects a specific file within a multi-file preview task (the
+ file_path key from the task status). Omitted = first available file.
+ """
+ _, error = _require_preview_task(task_service, user, task_id)
+ if error is not None:
+ return error
+
+ preview = preview_service.get_docling_preview(user.user_id, task_id, file_path=file)
+ if preview is None:
+ return JSONResponse({"error": "Parse preview not available yet"}, status_code=404)
+
+ return JSONResponse(
+ {
+ "task_id": task_id,
+ "document": preview["document"],
+ "stats": preview["stats"],
+ "expires_at": preview["expires_at"],
+ "document_id": preview.get("document_id"),
+ "file_path": preview.get("file_path"),
+ "filename": preview.get("filename"),
+ }
+ )
+
+
async def get_index_proof(
task_id: str,
preview_service: Annotated[Any, Depends(get_ingest_preview_service)],
diff --git a/src/app/container.py b/src/app/container.py
index 27d538488..d001179c7 100644
--- a/src/app/container.py
+++ b/src/app/container.py
@@ -122,6 +122,7 @@ async def initialize_services():
docling_service=clients.docling_service,
document_index_writer=document_index_writer,
ingest_token_service=langflow_ingest_token_service,
+ ingest_preview_service=ingest_preview_service,
)
langflow_mcp_service = LangflowMCPService()
diff --git a/src/app/routes/internal.py b/src/app/routes/internal.py
index c9703e833..8ecb56786 100644
--- a/src/app/routes/internal.py
+++ b/src/app/routes/internal.py
@@ -76,7 +76,13 @@ def register_internal_routes(app: FastAPI):
app.add_api_route("/upload_options", upload.upload_options, methods=["GET"], tags=["internal"])
app.add_api_route("/upload_bucket", upload.upload_bucket, methods=["POST"], tags=["internal"])
- # Ingest preview endpoint (index proof for preview-mode ingests)
+ # Ingest preview endpoints (Docling layout + index proof for preview-mode ingests)
+ app.add_api_route(
+ "/ingest/preview/{task_id}/docling",
+ ingest_preview.get_parse_preview,
+ methods=["GET"],
+ tags=["internal"],
+ )
app.add_api_route(
"/ingest/preview/{task_id}/index-proof",
ingest_preview.get_index_proof,
diff --git a/src/models/processors.py b/src/models/processors.py
index 0cd6498fd..3359cf747 100644
--- a/src/models/processors.py
+++ b/src/models/processors.py
@@ -861,6 +861,7 @@ class ConnectorFileProcessor(TaskProcessor):
ingest_settings: dict[str, Any] | None = None,
replace_duplicates: bool = False,
connector_type: str | None = None,
+ preview_mode: bool = False,
shared: bool = False,
):
super().__init__(
@@ -878,6 +879,7 @@ class ConnectorFileProcessor(TaskProcessor):
self.ingest_settings = ingest_settings
self.replace_duplicates = replace_duplicates
self.connector_type = connector_type
+ self.preview_mode = preview_mode
self.shared = shared
async def _reconcile_shared_owner(self, filename: str) -> None:
@@ -1225,6 +1227,7 @@ class ConnectorFileProcessor(TaskProcessor):
if self.connector_service.task_service
else None,
file_task=file_task,
+ document_id=document.id,
connector_file_id=document.id,
source_url=document.source_url,
allowed_users=allowed_users,
@@ -1233,6 +1236,9 @@ class ConnectorFileProcessor(TaskProcessor):
allowed_principal_labels=allowed_principal_labels,
original_filename=file_task.filename,
original_mimetype=document.mimetype,
+ preview_mode=self.preview_mode,
+ upload_task_id=upload_task.task_id,
+ preview_user_id=self.user_id,
)
# Langflow returns "success" even when no text was extracted
# (e.g. image files without OCR). Verify the document actually
@@ -1459,6 +1465,7 @@ class LangflowFileProcessor(TaskProcessor):
replace_duplicates: bool = False,
connector_type: str = "local",
docling_polling_service=None,
+ preview_mode: bool = False,
):
super().__init__()
self.langflow_file_service = langflow_file_service
@@ -1473,6 +1480,7 @@ class LangflowFileProcessor(TaskProcessor):
self.replace_duplicates = replace_duplicates
self.connector_type = connector_type
self.docling_polling_service = docling_polling_service
+ self.preview_mode = preview_mode
async def process_item(self, upload_task: UploadTask, item: str, file_task: FileTask) -> None:
"""Process a file path using LangflowFileService upload_and_ingest_file"""
@@ -1555,6 +1563,9 @@ class LangflowFileProcessor(TaskProcessor):
document_id=file_hash,
original_filename=original_filename,
original_mimetype=original_mimetype,
+ preview_mode=self.preview_mode,
+ upload_task_id=upload_task.task_id,
+ preview_user_id=self.owner_user_id,
)
# Langflow returns "success" even when no text was extracted
diff --git a/src/services/docling_service.py b/src/services/docling_service.py
index 141194b77..f7df93865 100644
--- a/src/services/docling_service.py
+++ b/src/services/docling_service.py
@@ -153,6 +153,7 @@ class DoclingService:
*,
ocr_override: bool | None = None,
picture_descriptions_override: bool | None = None,
+ preview_mode: bool = False,
) -> dict[str, Any]:
"""Build the options payload for docling from OpenRAG configs, incorporating VLM settings if enabled."""
from services.watsonx_iam import WatsonxIamError, get_iam_token
@@ -173,7 +174,18 @@ class DoclingService:
picture_descriptions=is_pic_desc_enabled,
)
- options = {"to_formats": "json", "image_export_mode": "placeholder", **preset}
+ image_export_mode = "embedded" if preview_mode else "placeholder"
+ options = {"to_formats": "json", "image_export_mode": image_export_mode, **preset}
+ if preview_mode:
+ # The live preview renders full-page screenshots with bounding-box
+ # overlays (docling-img). docling-serve only produces those when
+ # include_page_images is enabled (it defaults to false), so request
+ # both page renderings and picture images explicitly. Without this
+ # the preview shows neither the page image nor the parsed boxes.
+ # Non-paged formats (docx/pptx/…) still parse to JSON texts/tables,
+ # which the preview renders directly as labeled blocks.
+ options["include_page_images"] = True
+ options["include_images"] = True
# If picture descriptions are enabled, configure custom/local VLM model
if is_pic_desc_enabled and knowledge_config.vlm_enabled:
@@ -289,6 +301,7 @@ class DoclingService:
*,
ocr: bool | None = None,
picture_descriptions: bool | None = None,
+ preview_mode: bool = False,
) -> str:
"""
Upload a file to Docling Serve asynchronously using direct multipart/form-data upload.
@@ -296,6 +309,7 @@ class DoclingService:
options = await self._build_docling_options_async(
ocr_override=ocr,
picture_descriptions_override=picture_descriptions,
+ preview_mode=preview_mode,
)
headers = self._get_auth_headers(user_id, auth_header)
diff --git a/src/services/ingest_preview_service.py b/src/services/ingest_preview_service.py
index d63ecf54a..4d04b2276 100644
--- a/src/services/ingest_preview_service.py
+++ b/src/services/ingest_preview_service.py
@@ -1,9 +1,13 @@
-"""Index proof helpers for preview-mode ingest (no Docling document cache)."""
+"""Index proof helpers and ephemeral Docling parse preview cache."""
from __future__ import annotations
+import time
+from dataclasses import dataclass
from typing import Any
+from cachetools import TTLCache
+
from config.settings import get_index_name
from models.tasks import IngestionPhase
from utils.logging_config import get_logger
@@ -13,6 +17,25 @@ logger = get_logger(__name__)
TEXT_PREVIEW_MAX_LENGTH = 240
INDEX_PROOF_MAX_CHUNKS = 200
+# Cap how many per-file previews we retain for a single upload task. Preview
+# documents can embed full-page rasters, so an unbounded folder/connector sync
+# could otherwise grow the in-memory cache without limit. Previews beyond this
+# count are simply not cached (the UI falls back to the local/expired state).
+MAX_PREVIEWS_PER_TASK = 50
+
+# Global bound for the in-memory Docling preview cache (TTL + maxsize).
+MAX_PREVIEW_CACHE_ENTRIES = 500
+
+
+def summarize_docling_document(document: dict[str, Any]) -> dict[str, int]:
+ """Return layout element counts for a DoclingDocument dict."""
+ return {
+ "page_count": len(document.get("pages") or []),
+ "text_count": len(document.get("texts") or []),
+ "table_count": len(document.get("tables") or []),
+ "picture_count": len(document.get("pictures") or []),
+ }
+
def _chunk_sequence(chunk_id: str | None) -> int:
"""Numeric suffix from chunk ``_id`` (last underscore-delimited segment)."""
@@ -45,8 +68,115 @@ def _extract_hit_total(hits_section: dict[str, Any], fallback: int) -> int:
return fallback
+@dataclass
+class _PreviewEntry:
+ user_id: str
+ file_path: str | None
+ document: dict[str, Any]
+ stats: dict[str, int]
+ expires_at: float
+ document_id: str | None = None
+ filename: str | None = None
+
+
class IngestPreviewService:
- """Stateless helper for preview-mode index proof queries."""
+ """Index-proof queries plus in-memory TTL cache for Docling parse previews.
+
+ Cache entries are keyed per file (``(user_id, task_id, file_path)``) so a
+ single preview-mode upload task can hold a parse preview for each of its
+ files. ``file_path`` may be ``None`` for legacy single-file callers.
+ """
+
+ def __init__(self, ttl_seconds: int = 1800):
+ self._ttl_seconds = max(ttl_seconds, 1)
+ self._entries: TTLCache[tuple[str, str, str | None], _PreviewEntry] = TTLCache(
+ maxsize=MAX_PREVIEW_CACHE_ENTRIES,
+ ttl=self._ttl_seconds,
+ )
+ # Per-task file_path set for O(task) cap checks (not a full-cache scan).
+ self._task_keys: dict[tuple[str, str], set[str | None]] = {}
+
+ def _prune_task_keys(self, user_id: str, task_id: str) -> set[str | None]:
+ """Drop file paths whose cache entries already expired or were evicted."""
+ task_key = (user_id, task_id)
+ known = self._task_keys.get(task_key)
+ if not known:
+ return set()
+ alive = {file_path for file_path in known if (user_id, task_id, file_path) in self._entries}
+ if alive:
+ self._task_keys[task_key] = alive
+ else:
+ self._task_keys.pop(task_key, None)
+ return alive
+
+ def store_docling_preview(
+ self,
+ user_id: str,
+ task_id: str,
+ document: dict[str, Any],
+ *,
+ file_path: str | None = None,
+ document_id: str | None = None,
+ filename: str | None = None,
+ ) -> None:
+ key = (user_id, task_id, file_path)
+ task_key = (user_id, task_id)
+ alive = self._prune_task_keys(user_id, task_id)
+ if key not in self._entries and len(alive) >= MAX_PREVIEWS_PER_TASK:
+ logger.debug(
+ "Skipping ingest parse preview cache (per-task cap reached)",
+ user_id=user_id,
+ task_id=task_id,
+ file_path=file_path,
+ cap=MAX_PREVIEWS_PER_TASK,
+ )
+ return
+ stats = summarize_docling_document(document)
+ self._entries[key] = _PreviewEntry(
+ user_id=user_id,
+ file_path=file_path,
+ filename=filename,
+ document=document,
+ stats=stats,
+ expires_at=time.time() + self._ttl_seconds,
+ document_id=document_id,
+ )
+ alive.add(file_path)
+ self._task_keys[task_key] = alive
+ logger.info(
+ "Stored ingest parse preview",
+ user_id=user_id,
+ task_id=task_id,
+ file_path=file_path,
+ page_count=stats["page_count"],
+ text_count=stats["text_count"],
+ table_count=stats["table_count"],
+ )
+
+ def get_docling_preview(
+ self,
+ user_id: str,
+ task_id: str,
+ file_path: str | None = None,
+ ) -> dict[str, Any] | None:
+ if file_path is not None:
+ entry = self._entries.get((user_id, task_id, file_path))
+ else:
+ entry = None
+ for known_path in self._prune_task_keys(user_id, task_id):
+ entry = self._entries.get((user_id, task_id, known_path))
+ if entry is not None:
+ break
+ if entry is None:
+ return None
+ return {
+ "document": entry.document,
+ "stats": entry.stats,
+ "expires_at": entry.expires_at,
+ "document_id": entry.document_id,
+ "file_path": entry.file_path,
+ "filename": entry.filename,
+ }
async def get_index_proof(
self,
diff --git a/src/services/langflow_file_service.py b/src/services/langflow_file_service.py
index 528100f0a..3fcf938d0 100644
--- a/src/services/langflow_file_service.py
+++ b/src/services/langflow_file_service.py
@@ -36,12 +36,15 @@ class LangflowFileService:
docling_service=None,
document_index_writer=None,
ingest_token_service=None,
- ) -> None:
+ ingest_preview_service=None,
+ ):
+
self.flow_id_ingest = LANGFLOW_INGEST_FLOW_ID
self.flows_service = flows_service
self.docling_service = docling_service
self.document_index_writer = document_index_writer
self.ingest_token_service = ingest_token_service
+ self.ingest_preview_service = ingest_preview_service
self.flow_id_url_ingest = LANGFLOW_URL_INGEST_FLOW_ID
self._embedding_dimension_cache: dict[str, int] = {}
@@ -890,6 +893,47 @@ class LangflowFileService:
raise last_error
raise RuntimeError("Unable to validate/import URL ingest flow")
+ async def _cache_docling_preview_if_enabled(
+ self,
+ *,
+ preview_mode: bool,
+ upload_task_id: str | None,
+ preview_user_id: str | None,
+ docling_task_id: str,
+ document_id: str | None,
+ owner: str | None,
+ jwt_token: str | None,
+ file_path: str | None = None,
+ filename: str | None = None,
+ ) -> None:
+ if not (
+ preview_mode and self.ingest_preview_service and upload_task_id and preview_user_id
+ ):
+ return
+ try:
+ doc_json = await self.docling_service.fetch_task_result(
+ docling_task_id,
+ user_id=owner,
+ auth_header=jwt_token,
+ )
+ self.ingest_preview_service.store_docling_preview(
+ preview_user_id,
+ upload_task_id,
+ doc_json,
+ file_path=file_path,
+ document_id=document_id,
+ filename=filename,
+ )
+ except Exception as preview_error:
+ logger.warning(
+ "[LF] Failed to cache parse preview after Docling success",
+ extra={
+ "task_id": docling_task_id,
+ "upload_task_id": upload_task_id,
+ "error": str(preview_error),
+ },
+ )
+
async def submit_to_docling(
self,
filename: str,
@@ -899,6 +943,7 @@ class LangflowFileService:
*,
ocr: bool | None = None,
picture_descriptions: bool | None = None,
+ preview_mode: bool = False,
) -> str:
"""Upload a file to Docling Serve and return the task_id immediately.
@@ -919,6 +964,7 @@ class LangflowFileService:
auth_header=jwt_token,
ocr=ocr,
picture_descriptions=picture_descriptions,
+ preview_mode=preview_mode,
)
logger.debug(
"[LF] Docling submission accepted",
@@ -954,6 +1000,9 @@ class LangflowFileService:
allowed_principal_labels: list[dict[str, Any]] | None = None,
original_filename: str | None = None,
original_mimetype: str | None = None,
+ preview_mode: bool = False,
+ upload_task_id: str | None = None,
+ preview_user_id: str | None = None,
) -> dict[str, Any]:
"""
Two-phase Docling upload + Langflow ingest operation.
@@ -1001,6 +1050,7 @@ class LangflowFileService:
jwt_token=jwt_token,
ocr=ocr_override,
picture_descriptions=pic_desc_override,
+ preview_mode=preview_mode,
)
if file_task is not None:
@@ -1052,6 +1102,17 @@ class LangflowFileService:
if file_task is not None:
file_task.docling_status = DoclingPhaseStatus.SUCCESS
+ await self._cache_docling_preview_if_enabled(
+ preview_mode=preview_mode,
+ upload_task_id=upload_task_id,
+ preview_user_id=preview_user_id,
+ docling_task_id=task_id,
+ document_id=document_id,
+ owner=owner,
+ jwt_token=jwt_token,
+ file_path=file_task.file_path if file_task is not None else None,
+ filename=filename,
+ )
logger.info(
"[LF] Docling conversion ready; proceeding to Langflow",
extra={
diff --git a/src/services/task_service.py b/src/services/task_service.py
index aa60542c1..d6ad68919 100644
--- a/src/services/task_service.py
+++ b/src/services/task_service.py
@@ -338,6 +338,7 @@ class TaskService:
replace_duplicates=replace_duplicates,
connector_type=connector_type,
docling_polling_service=self.docling_polling_service,
+ preview_mode=preview_mode,
)
return await self.create_custom_task(
user_id,
diff --git a/src/utils/ingest_preview_flag.py b/src/utils/ingest_preview_flag.py
index a6db0f6d2..4e92b9876 100644
--- a/src/utils/ingest_preview_flag.py
+++ b/src/utils/ingest_preview_flag.py
@@ -1,7 +1,11 @@
"""Feature-flag gating for the preview-mode ingest backend."""
from config.settings import is_ingest_preview_flag_enabled
-from utils.run_mode_utils import is_run_mode_oss, is_run_mode_saas
+from utils.run_mode_utils import RUN_MODE_OSS, get_run_mode
+
+# Run modes eligible once OPENRAG_INGEST_PREVIEW_ENABLED is on.
+# SaaS omitted until product approval — re-add RUN_MODE_SAAS here to restore.
+_INGEST_PREVIEW_RUN_MODES = frozenset({RUN_MODE_OSS})
def is_ingest_preview_enabled() -> bool:
@@ -10,12 +14,13 @@ def is_ingest_preview_enabled() -> bool:
Gated behind an explicit opt-in feature flag so merging to main does not
change behavior for existing installs. The flag defaults to ``false`` --
set ``OPENRAG_INGEST_PREVIEW_ENABLED=true`` to turn it on. The run-mode
- check is AND-ed with the flag: preview is only ever available in OSS and
- SaaS run modes (never on_prem), and even there only when the flag is set.
+ check is AND-ed with the flag: preview is only available for modes in
+ ``_INGEST_PREVIEW_RUN_MODES`` (currently OSS only; SaaS deferred pending
+ product approval), and even there only when the flag is set.
The raw env read lives in ``config.settings`` (the single place that owns
``os.environ`` parsing); this module only layers the run-mode gate on top.
"""
if not is_ingest_preview_flag_enabled():
return False
- return is_run_mode_oss() or is_run_mode_saas()
+ return get_run_mode() in _INGEST_PREVIEW_RUN_MODES
diff --git a/tests/unit/api/test_connector_sync_response.py b/tests/unit/api/test_connector_sync_response.py
index c8c9ff64d..c68fdc602 100644
--- a/tests/unit/api/test_connector_sync_response.py
+++ b/tests/unit/api/test_connector_sync_response.py
@@ -122,7 +122,7 @@ def _preview_service_with_working_connection():
@pytest.mark.asyncio
async def test_connector_sync_passes_preview_mode_to_sync_specific_files(monkeypatch):
- """body.preview=True threads preview_mode=True into sync_specific_files (OSS/SaaS)."""
+ """body.preview=True threads preview_mode=True into sync_specific_files."""
from api import connectors as connectors_api
from api import documents as documents_api
diff --git a/tests/unit/api/test_ingest_preview.py b/tests/unit/api/test_ingest_preview.py
index a4d64f471..3bcf040ce 100644
--- a/tests/unit/api/test_ingest_preview.py
+++ b/tests/unit/api/test_ingest_preview.py
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.responses import JSONResponse
-from api.ingest_preview import get_index_proof
+from api.ingest_preview import get_index_proof, get_parse_preview
from session_manager import User
@@ -23,6 +23,14 @@ def user():
@pytest.fixture
def preview_service():
service = MagicMock()
+ service.get_docling_preview.return_value = {
+ "document": {"pages": [{"page_no": 1}], "texts": [], "tables": [], "pictures": []},
+ "stats": {"page_count": 1, "text_count": 0, "table_count": 0, "picture_count": 0},
+ "expires_at": 9999999999.0,
+ "document_id": "hash-1",
+ "file_path": "/tmp/a.pdf",
+ "filename": "a.pdf",
+ }
service.get_index_proof = AsyncMock(
return_value={
"ready": True,
@@ -47,6 +55,67 @@ def task_service():
return service
+async def test_get_parse_preview_returns_docling_document(user, preview_service, task_service):
+ response = await get_parse_preview(
+ task_id="task-1",
+ preview_service=preview_service,
+ task_service=task_service,
+ user=user,
+ )
+
+ assert isinstance(response, JSONResponse)
+ assert response.status_code == 200
+ body = response.body.decode()
+ assert "document" in body
+ assert "stats" in body
+ preview_service.get_docling_preview.assert_called_once_with("user-1", "task-1", file_path=None)
+
+
+async def test_get_parse_preview_passes_file_param(user, preview_service, task_service):
+ response = await get_parse_preview(
+ task_id="task-1",
+ preview_service=preview_service,
+ task_service=task_service,
+ user=user,
+ file="/tmp/b.pdf",
+ )
+
+ assert response.status_code == 200
+ preview_service.get_docling_preview.assert_called_once_with(
+ "user-1", "task-1", file_path="/tmp/b.pdf"
+ )
+
+
+async def test_get_parse_preview_not_found(user, preview_service, task_service):
+ preview_service.get_docling_preview.return_value = None
+
+ response = await get_parse_preview(
+ task_id="missing",
+ preview_service=preview_service,
+ task_service=task_service,
+ user=user,
+ )
+
+ assert response.status_code == 404
+
+
+async def test_get_parse_preview_unavailable_when_disabled(user, preview_service, task_service):
+ with patch("api.ingest_preview.is_ingest_preview_enabled", return_value=False):
+ response = await get_parse_preview(
+ task_id="task-1",
+ preview_service=preview_service,
+ task_service=task_service,
+ user=user,
+ )
+
+ assert response.status_code == 404
+ preview_service.get_docling_preview.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_get_index_proof_uses_validated_upload_task_without_refetch(
user, preview_service, task_service
diff --git a/tests/unit/services/test_ingest_preview_service.py b/tests/unit/services/test_ingest_preview_service.py
index 2aeb6745b..0b8424d35 100644
--- a/tests/unit/services/test_ingest_preview_service.py
+++ b/tests/unit/services/test_ingest_preview_service.py
@@ -1,18 +1,66 @@
-"""Tests for preview-mode index proof helpers."""
+"""Tests for preview-mode Docling cache and index proof helpers."""
+import time
from unittest.mock import AsyncMock
import pytest
from models.tasks import FileTask, IngestionPhase, TaskStatus, UploadTask
from services.ingest_preview_service import (
+ MAX_PREVIEWS_PER_TASK,
IngestPreviewService,
_chunk_sequence,
_extract_hit_total,
_sort_hits,
+ summarize_docling_document,
)
+def test_summarize_docling_document_counts_layout_elements():
+ doc = {
+ "pages": [{"page_no": 1}, {"page_no": 2}],
+ "texts": [{"text": "Title"}, {"text": "Body"}],
+ "tables": [{"data": {}}],
+ "pictures": [{"image": {}}],
+ }
+
+ stats = summarize_docling_document(doc)
+
+ assert stats == {
+ "page_count": 2,
+ "text_count": 2,
+ "table_count": 1,
+ "picture_count": 1,
+ }
+
+
+def test_store_and_get_docling_preview():
+ service = IngestPreviewService(ttl_seconds=300)
+ doc = {"pages": [{"page_no": 1}], "texts": [], "tables": [], "pictures": []}
+
+ service.store_docling_preview("user-1", "task-1", doc, document_id="hash-abc")
+
+ preview = service.get_docling_preview("user-1", "task-1")
+ assert preview is not None
+ assert preview["document"] == doc
+ assert preview["stats"]["page_count"] == 1
+ assert preview["document_id"] == "hash-abc"
+ assert preview["expires_at"] > time.time()
+
+
+def test_store_docling_preview_caps_entries_per_task():
+ service = IngestPreviewService(ttl_seconds=300)
+ doc = {"pages": [{"page_no": 1}], "texts": [], "tables": [], "pictures": []}
+
+ for i in range(MAX_PREVIEWS_PER_TASK + 5):
+ service.store_docling_preview(
+ "user-1", "task-1", doc, file_path=f"/tmp/file-{i}.pdf", document_id=f"hash-{i}"
+ )
+
+ stored = [k for k in service._entries if k[0] == "user-1" and k[1] == "task-1"]
+ assert len(stored) == MAX_PREVIEWS_PER_TASK
+
+
def test_chunk_sequence_parses_numeric_suffix():
assert _chunk_sequence("hash-abc_10") == 10
assert _chunk_sequence("hash-abc_2") == 2
diff --git a/tests/unit/test_docling_service.py b/tests/unit/test_docling_service.py
index 78f84d536..c1a87ca2c 100644
--- a/tests/unit/test_docling_service.py
+++ b/tests/unit/test_docling_service.py
@@ -197,6 +197,27 @@ async def test_build_docling_options_toggles(docling_service):
assert options["do_ocr"] is True
assert options["do_picture_description"] is False
assert options["to_formats"] == "json"
+ assert options["image_export_mode"] == "placeholder"
+ assert "include_page_images" not in options
+ assert "include_images" not in options
+
+
+async def test_build_docling_options_preview_mode_embeds_page_images(docling_service):
+ """Preview mode requests embedded page rasters for PDF bbox overlays."""
+ mock_config = MagicMock()
+ mock_config.knowledge.table_structure = False
+ mock_config.knowledge.ocr = False
+ mock_config.knowledge.picture_descriptions = False
+ mock_config.knowledge.vlm_enabled = False
+
+ with patch("services.docling_service.get_openrag_config", return_value=mock_config):
+ options = await docling_service._build_docling_options_async(preview_mode=True)
+
+ assert options["to_formats"] == "json"
+ assert options["image_export_mode"] == "embedded"
+ assert options["include_page_images"] is True
+ assert options["include_images"] is True
def test_preset_configs_macos():
diff --git a/tests/unit/test_provider_error_formatting.py b/tests/unit/test_provider_error_formatting.py
index 6a36d43c8..3dfd63c45 100644
--- a/tests/unit/test_provider_error_formatting.py
+++ b/tests/unit/test_provider_error_formatting.py
@@ -25,6 +25,20 @@ def test_parse_ibm_iam_error_message():
assert format_provider_error_message(raw) == "Provided API key is Invalid."
+def test_format_dedupes_identical_auth_failures_with_different_request_ids():
+ first = (
+ 'Failed to authenticate with IBM Watson: {"errorCode":"BXNIM0415E",'
+ '"errorMessage":"Provided API key could not be found.",'
+ '"context":{"requestId":"req-1"}}'
+ )
+ second = (
+ 'Failed to authenticate with IBM Watson: {"errorCode":"BXNIM0415E",'
+ '"errorMessage":"Provided API key could not be found.",'
+ '"context":{"requestId":"req-2"}}'
+ )
+ assert format_provider_error_message(first) == format_provider_error_message(second)
+
+
def test_format_extracts_json_with_trailing_text():
raw = (
"Failed to initialize IBM WatsonX embedding model: Attempt of authenticating "
diff --git a/tests/unit/utils/test_ingest_preview_flag.py b/tests/unit/utils/test_ingest_preview_flag.py
index 46233f59c..6e351f1ac 100644
--- a/tests/unit/utils/test_ingest_preview_flag.py
+++ b/tests/unit/utils/test_ingest_preview_flag.py
@@ -14,13 +14,19 @@ def test_disabled_by_default(monkeypatch, run_mode):
@pytest.mark.parametrize("flag", ["true", "1", "yes", "on", "TRUE"])
[email protected]("run_mode", ["oss", "saas"])
-def test_enabled_when_flag_and_supported_run_mode(monkeypatch, flag, run_mode):
- monkeypatch.setenv("OPENRAG_RUN_MODE", run_mode)
+def test_enabled_when_flag_and_oss(monkeypatch, flag):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "oss")
monkeypatch.setenv("OPENRAG_INGEST_PREVIEW_ENABLED", flag)
assert is_ingest_preview_enabled() is True
+def test_flag_does_not_enable_saas(monkeypatch):
+ """SaaS is temporarily off the allowlist pending product approval."""
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setenv("OPENRAG_INGEST_PREVIEW_ENABLED", "true")
+ assert is_ingest_preview_enabled() is False
+
+
def test_flag_does_not_enable_on_prem(monkeypatch):
"""The flag is AND-ed with the run mode: on_prem is never eligible."""
monkeypatch.setenv("OPENRAG_RUN_MODE", "on_prem")