OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
"use client";
import { useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, FileSearch, FolderOpen, RefreshCw } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import type { useSyncConnector } from "@/app/api/mutations/useSyncConnector";
import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
import { IngestSettings } from "@/components/cloud-picker/ingest-settings";
import { validateIngestSettingsOrToast } from "@/components/cloud-picker/types";
import { DuplicateHandlingDialog } from "@/components/duplicate-handling-dialog";
import { FileBrowserDialog } from "@/components/file-browser-dialog";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/contexts/auth-context";
import { useSessionIngestSettings } from "@/hooks/useSessionIngestSettings";
import { trackProcessFailure, trackStartProcess } from "@/lib/analytics";
import { apiClient } from "@/lib/api-client";
interface BucketDuplicateFile {
id: string;
name: string;
mimeType: string;
downloadUrl?: string;
size?: number;
}
interface BucketDuplicateCheckResponse {
duplicate_names?: string[];
duplicate_count?: number;
duplicate_files?: BucketDuplicateFile[];
non_duplicate_files?: BucketDuplicateFile[];
}
export interface SharedBucketViewProps {
connector: any;
buckets: Array<{ name: string; ingested_count: number }> | undefined;
isLoading: boolean;
bucketsError?: Error | null;
onRefetch: () => void;
invalidateQueryKey: readonly unknown[];
syncMutation: ReturnType<typeof useSyncConnector>;
addTask: (
id: string,
options?: { connectorType?: string; source?: string },
) => void;
onBack: () => void;
onDone: () => void;
/** When true, show the "Make documents available to all users" toggle. COS ingestion only. */
showShared?: boolean;
/** Buckets to pre-select once `buckets` has loaded, e.g. from saved connector defaults. */
initialSelectedBuckets?: string[];
/** Singular label for the resource type, e.g. "bucket" or "container". Defaults to "container". */
resourceLabel?: string;
/** Plural label for the resource type, e.g. "buckets" or "containers". Defaults to "containers". */
resourceLabelPlural?: string;
}
export function SharedBucketView({
connector,
buckets,
isLoading,
bucketsError,
onRefetch,
invalidateQueryKey,
syncMutation,
resourceLabel = "container",
resourceLabelPlural = "containers",
addTask,
onBack,
onDone,
showShared = false,
initialSelectedBuckets,
}: SharedBucketViewProps) {
const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
const queryClient = useQueryClient();
const { isAuthenticated, isNoAuthMode } = useAuth();
const { data: apiSettings } = useGetSettingsQuery({
enabled: isAuthenticated || isNoAuthMode,
});
const showIngestSettings =
apiSettings?.show_provider_ingest_settings ?? false;
// The shared toggle can be exposed on its own (e.g. for SaaS deployments that
// hide the general per-upload ingest tuning knobs) via a dedicated flag.
const showSharedToggle =
showShared &&
(showIngestSettings || (apiSettings?.show_shared_upload_toggle ?? false));
const [selectedBuckets, setSelectedBuckets] = useState<Set<string>>(
new Set(),
);
const hasAppliedInitial = useRef(false);
const [ingestSettings, setIngestSettings] = useSessionIngestSettings();
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [browseDialogBucket, setBrowseDialogBucket] = useState<string | null>(
null,
);
const [isCheckingDuplicates, setIsCheckingDuplicates] = useState(false);
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
const [pendingDuplicates, setPendingDuplicates] = useState<{
duplicateNames: string[];
duplicateCount: number;
nonDuplicateFiles: BucketDuplicateFile[];
} | null>(null);
const isOverwriteConfirmedRef = useRef(false);
// Tracks the "ingest anyway" toast shown when the duplicate check fails, so
// it can be dismissed instead of left to fire its captured (and
// increasingly stale) request after the selection changes or the view
// goes away.
const checkFailedToastIdRef = useRef<string | number | null>(null);
useEffect(() => {
if (
!hasAppliedInitial.current &&
buckets?.length &&
initialSelectedBuckets?.length
) {
hasAppliedInitial.current = true;
if (selectedBuckets.size === 0) {
const valid = initialSelectedBuckets.filter((name) =>
buckets.some((b) => b.name === name),
);
if (valid.length) {
setSelectedBuckets(new Set(valid));
}
}
}
}, [buckets, initialSelectedBuckets, selectedBuckets.size]); // eslint-disable-line react-hooks/exhaustive-deps
// A changed selection or ingest setting means the "ingest anyway" toast's
// captured request no longer matches what the user is looking at, so drop
// it rather than let a later click submit the old choice.
useEffect(() => {
if (checkFailedToastIdRef.current !== null) {
toast.dismiss(checkFailedToastIdRef.current);
checkFailedToastIdRef.current = null;
}
}, [selectedBuckets, ingestSettings, showSharedToggle]);
// The toast outlives the component by default; dismiss it on unmount so it
// can't fire a sync whose onSuccess/onError callbacks (addTask, onDone)
// belong to a view that's no longer there.
useEffect(() => {
return () => {
if (checkFailedToastIdRef.current !== null) {
toast.dismiss(checkFailedToastIdRef.current);
}
};
}, []);
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: invalidateQueryKey });
};
const trackIngestTasks = (taskIds?: string[]) => {
for (const id of taskIds ?? []) {
addTask(id, { connectorType: connector.type, source: "connector" });
}
};
const toggleBucket = (bucketName: string) => {
setSelectedBuckets((prev) => {
const next = new Set(prev);
if (next.has(bucketName)) {
next.delete(bucketName);
} else {
next.add(bucketName);
}
return next;
});
};
const onSyncSettled = () => {
invalidate();
};
const onSyncError = (err: unknown) => {
trackProcessFailure({
processType: "Ingestion",
process: "Document Upload",
category: "Knowledge",
source: "connector",
connector_type: connector.type,
resultValue: err instanceof Error ? err.message : "Sync failed",
});
toast.error(err instanceof Error ? err.message : "Sync failed");
};
const onSyncSuccess = (result: { task_ids?: string[]; message?: string }) => {
onSyncSettled();
if (result.task_ids?.length) {
// The container path may return two tasks (new files + changed files);
// track them all.
for (const id of result.task_ids) {
addTask(id, {
connectorType: connector.type,
source: "connector",
});
}
onDone();
} else {
toast.info(result.message ?? "No files found in the selected buckets.");
}
};
// Full bucket sync: backend classifies new/changed/unchanged itself and
// re-ingests both new and changed blobs. With `replaceDuplicates`, it instead
// re-ingests the whole selection and replaces what is already indexed — the
// overwrite path. Either way the bucket names travel instead of the file
// list, so the request stays the same size for a 10-object bucket and a
// 10,000-object one.
const runBucketSync = (replaceDuplicates = false) => {
syncMutation.mutate(
{
connectorType: connector.type,
body: {
connection_id: connector.connectionId!,
selected_files: [],
bucket_filter: Array.from(selectedBuckets),
settings: ingestSettings,
replace_duplicates: replaceDuplicates,
shared: showSharedToggle
? (ingestSettings.shared ?? false)
: undefined,
},
},
{ onSuccess: onSyncSuccess, onError: onSyncError },
);
};
// Sync an explicit subset of the listing — how "skip duplicates" ingests
// only the files that are not already indexed. (Overwrite goes through
// runBucketSync(true) instead: it needs the whole selection, and naming the
// buckets says that in one line.)
const runSelectedFilesSync = (files: BucketDuplicateFile[]) => {
syncMutation.mutate(
{
connectorType: connector.type,
body: {
connection_id: connector.connectionId!,
selected_files: files,
settings: ingestSettings,
replace_duplicates: false,
shared: showSharedToggle
? (ingestSettings.shared ?? false)
: undefined,
},
},
{ onSuccess: onSyncSuccess, onError: onSyncError },
);
};
const ingestSelected = async () => {
if (!validateIngestSettingsOrToast(ingestSettings)) return;
trackStartProcess({
processType: "Ingestion",
process: "Document Upload",
category: "Knowledge",
source: "connector",
connector_type: connector.type,
total_buckets: selectedBuckets.size,
});
setIsCheckingDuplicates(true);
try {
const checkResponse = await apiClient.post(
`/connectors/${connector.type}/check-duplicates`,
{
connection_id: connector.connectionId,
bucket_filter: Array.from(selectedBuckets),
},
);
if (checkResponse.status < 200 || checkResponse.status >= 300) {
throw new Error(`Duplicate check failed: ${checkResponse.statusText}`);
}
const checkData = checkResponse.data as BucketDuplicateCheckResponse;
const duplicateNames = checkData.duplicate_names || [];
const duplicateCount =
typeof checkData.duplicate_count === "number"
? checkData.duplicate_count
: duplicateNames.length;
if (duplicateCount === 0) {
runBucketSync();
return;
}
setPendingDuplicates({
duplicateNames,
duplicateCount,
nonDuplicateFiles: checkData.non_duplicate_files || [],
});
setDuplicateDialogOpen(true);
} catch (err) {
console.error("[Bucket Sync] Duplicate check failed:", err);
// Don't fall through to the sync by default. Proceeding would silently
// take the "skip duplicates" path — the ingest runs, every colliding
// file is skipped with "a file with this name already exists", and the
// user never got the choice the check exists to offer. That outcome is
// indistinguishable from "there were no duplicates", which is how it
// gets reported as the duplicate dialog not appearing.
//
// A deterministic timeout (the likeliest failure on a large bucket,
// since the check lists every blob in the selection) would otherwise
// leave no way to ingest that bucket from the UI at all, so the toast
// offers the old behavior as an explicit, conscious choice instead of a
// silent fallback.
checkFailedToastIdRef.current = toast.error(
"Could not check for existing files",
{
description:
"Nothing was ingested. Try again — if it keeps failing, the selected " +
`${resourceLabelPlural} may be too large to check. Ingesting anyway ` +
"skips files that already exist.",
action: {
label: "Ingest, skip existing",
onClick: () => runBucketSync(),
},
},
);
} finally {
setIsCheckingDuplicates(false);
}
};
const handleOverwriteDuplicates = () => {
if (!pendingDuplicates) return;
isOverwriteConfirmedRef.current = true;
runBucketSync(true);
setPendingDuplicates(null);
};
const handleDuplicateDialogOpenChange = (open: boolean) => {
if (!open && pendingDuplicates) {
if (isOverwriteConfirmedRef.current) {
// Overwrite already submitted in handleOverwriteDuplicates; this close
// event fires immediately after and would otherwise re-enter the
// "skip duplicates" branch.
isOverwriteConfirmedRef.current = false;
} else {
const { nonDuplicateFiles, duplicateCount } = pendingDuplicates;
if (nonDuplicateFiles.length > 0) {
runSelectedFilesSync(nonDuplicateFiles);
} else {
toast.info(
`All ${duplicateCount} file(s) already exist and were skipped. Nothing was synced.`,
);
}
}
setPendingDuplicates(null);
}
setDuplicateDialogOpen(open);
};
return (
<>
<div className="mb-8 flex gap-2 items-center">
<Button variant="ghost" onClick={onBack} size="icon">
<ArrowLeft size={18} />
</Button>
<h2 className="text-xl text-[18px] font-semibold">
Add from {connector.name}
</h2>
</div>
<div className="max-w-3xl mx-auto space-y-4">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Select {resourceLabelPlural} to ingest.
</p>
<div className="flex items-center gap-2">
{selectedBuckets.size > 0 && (
<Button
variant="outline"
size="sm"
onClick={() => setSelectedBuckets(new Set())}
>
Deselect All
</Button>
)}
<Button
variant="outline"
size="sm"
onClick={() =>
setSelectedBuckets(new Set(buckets?.map((b) => b.name) ?? []))
}
disabled={isLoading || !buckets?.length}
>
Select All
</Button>
<Button
variant="outline"
size="sm"
onClick={onRefetch}
disabled={isLoading}
>
<RefreshCw
size={14}
className={isLoading ? "animate-spin" : ""}
/>
Refresh {capitalize(resourceLabelPlural)}
</Button>
</div>
</div>
{isLoading ? (
<div className="flex justify-center py-8">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
</div>
) : bucketsError ? (
<div className="rounded-lg border border-destructive/50 p-6 text-center text-destructive text-sm">
{bucketsError.message ||
"Failed to load buckets. Check your credentials and endpoint."}
</div>
) : !buckets?.length ? (
<div className="rounded-lg border p-6 text-center text-muted-foreground text-sm">
No {resourceLabelPlural} found. Check your credentials and endpoint.
</div>
) : (
<div className="rounded-lg border divide-y">
{buckets.map((bucket) => {
const isSelected = selectedBuckets.has(bucket.name);
return (
<div
key={bucket.name}
role="checkbox"
aria-checked={isSelected}
aria-label={bucket.name}
tabIndex={0}
className="flex items-center gap-[18px] px-4 py-3 cursor-pointer"
onClick={() => toggleBucket(bucket.name)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggleBucket(bucket.name);
}
}}
>
<div
className={`shrink-0 size-5 rounded-[6px] border-2 flex items-center justify-center transition-colors ${
isSelected
? "bg-foreground border-foreground"
: "border-muted-foreground/60"
}`}
>
{isSelected && (
<svg
viewBox="0 0 12 12"
fill="none"
className="size-3 text-background"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="2,6 5,9 10,3" />
</svg>
)}
</div>
<div className="flex items-center gap-4 flex-1 min-w-0">
<div className="bg-white/5 rounded-[10px] shrink-0 size-10 flex items-center justify-center">
<FolderOpen size={20} className="text-muted-foreground" />
</div>
<div className="flex flex-col gap-1 min-w-0">
<p className="font-medium text-sm leading-6">
{bucket.name}
</p>
{bucket.ingested_count > 0 && (
<p className="text-xs text-muted-foreground">
{bucket.ingested_count} document
{bucket.ingested_count !== 1 ? "s" : ""} ingested
</p>
)}
</div>
<Button
variant="outline"
size="sm"
className="shrink-0"
onClick={(e) => {
e.stopPropagation();
setBrowseDialogBucket(bucket.name);
}}
>
<FileSearch size={14} className="mr-1.5" />
Browse Files
</Button>
</div>
</div>
);
})}
</div>
)}
{(showIngestSettings || showSharedToggle) && (
<IngestSettings
isOpen={isSettingsOpen}
onOpenChange={setIsSettingsOpen}
settings={ingestSettings}
onSettingsChange={setIngestSettings}
showShared={showSharedToggle}
showAdvancedSettings={showIngestSettings}
/>
)}
</div>
<div className="max-w-3xl mx-auto mt-6 sticky bottom-0 left-0 right-0 pb-6 bg-background pt-4">
<div className="flex justify-between gap-3">
<Button
variant="ghost"
className="border bg-transparent border-border rounded-lg text-secondary-foreground"
onClick={onBack}
>
Back
</Button>
<Button
className="bg-foreground text-background hover:bg-foreground/90 font-semibold"
onClick={ingestSelected}
disabled={
syncMutation.isPending ||
isCheckingDuplicates ||
selectedBuckets.size === 0
}
loading={syncMutation.isPending || isCheckingDuplicates}
>
{syncMutation.isPending
? "Ingesting…"
: isCheckingDuplicates
? "Checking…"
: selectedBuckets.size > 0
? `Ingest ${selectedBuckets.size} ${selectedBuckets.size === 1 ? capitalize(resourceLabel) : capitalize(resourceLabelPlural)}`
: `Select ${capitalize(resourceLabelPlural)} to Ingest`}
</Button>
</div>
</div>
{connector.connectionId && browseDialogBucket && (
<FileBrowserDialog
open
onOpenChange={(open) => {
if (!open) setBrowseDialogBucket(null);
}}
connectorType={connector.type}
connectionId={connector.connectionId}
buckets={[browseDialogBucket]}
onIngestSuccess={(result) => {
invalidate();
if (result.task_ids?.length) {
trackIngestTasks(result.task_ids);
onDone();
} else {
toast.info(
result.message ?? "No files were queued for ingestion.",
);
}
}}
showShared={showSharedToggle}
ingestSettings={ingestSettings}
/>
)}
<DuplicateHandlingDialog
open={duplicateDialogOpen}
onOpenChange={handleDuplicateDialogOpenChange}
onOverwrite={handleOverwriteDuplicates}
isLoading={syncMutation.isPending}
duplicateNames={pendingDuplicates?.duplicateNames}
duplicateCount={pendingDuplicates?.duplicateCount}
/>
</>
);
}