Skip to content

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

Python

feat: add upgrade flows functionality (#2149)

Lucas Oliveiraa1930ba66267
diff --git a/frontend/app/api/mutations/useDismissFlowsUpdateMutation.ts b/frontend/app/api/mutations/useDismissFlowsUpdateMutation.ts
new file mode 100644
index 000000000..878cd89ca
--- /dev/null
+++ b/frontend/app/api/mutations/useDismissFlowsUpdateMutation.ts
@@ -0,0 +1,31 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+interface DismissFlowsUpdateVariables {
+ flow_types?: string[];
+}
+
+export function useDismissFlowsUpdateMutation() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (variables?: DismissFlowsUpdateVariables) => {
+ const response = await fetch("/api/settings/flows/dismiss-update", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(variables || {}),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to dismiss flow updates");
+ }
+
+ return response.json();
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: ["flows", "updates-available"],
+ });
+ },
+ });
+}
diff --git a/frontend/app/api/mutations/useUpdateFlowsMutation.ts b/frontend/app/api/mutations/useUpdateFlowsMutation.ts
new file mode 100644
index 000000000..d50cd0705
--- /dev/null
+++ b/frontend/app/api/mutations/useUpdateFlowsMutation.ts
@@ -0,0 +1,39 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+interface UpdateFlowsVariables {
+ flow_types: string[];
+ backup_custom: boolean;
+}
+
+export type FlowUpdateResult = {
+ flow_type: string;
+ success: boolean;
+ error?: string;
+ backup_path?: string;
+ backup_flow_id?: string;
+};
+
+export function useUpdateFlowsMutation() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (variables: UpdateFlowsVariables) => {
+ const response = await fetch("/api/settings/flows/update", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(variables),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to update flows");
+ }
+
+ const data = await response.json();
+ return data.results as FlowUpdateResult[];
+ },
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: ["flows"] });
+ },
+ });
+}
diff --git a/frontend/app/api/queries/useGetFlowsUpdatesQuery.ts b/frontend/app/api/queries/useGetFlowsUpdatesQuery.ts
new file mode 100644
index 000000000..d300f2364
--- /dev/null
+++ b/frontend/app/api/queries/useGetFlowsUpdatesQuery.ts
@@ -0,0 +1,23 @@
+import { useQuery } from "@tanstack/react-query";
+
+export type FlowUpdate = {
+ flow_type: "nudges" | "retrieval" | "ingest" | "url_ingest";
+ flow_id: string;
+ is_custom: boolean;
+ dismissed: boolean;
+};
+
+export function useGetFlowsUpdatesQuery(options?: { enabled?: boolean }) {
+ return useQuery({
+ queryKey: ["flows", "updates-available"],
+ queryFn: async () => {
+ const response = await fetch("/api/settings/flows/updates-available");
+ if (!response.ok) {
+ throw new Error("Failed to fetch flow updates");
+ }
+ const data = await response.json();
+ return data.updates as FlowUpdate[];
+ },
+ ...options,
+ });
+}
diff --git a/frontend/app/globals.css b/frontend/app/globals.css
index 3cd51f364..2c25ef15b 100644
--- a/frontend/app/globals.css
+++ b/frontend/app/globals.css
@@ -234,8 +234,116 @@
--component-icon: #0f62fe;
--flow-icon: #0043ce;
- --radius: 0rem; /* IBM uses sharp corners */
+ --radius: 0rem; /* IBM theme dialogs (Carbon design system style) */
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-content"],
+ [data-theme="ibm"] [role="dialog"] {
+ border-radius: 0 !important;
+ background-color: #262626 !important;
+ border: none !important;
+ color: #f4f4f4 !important;
+ padding: 1.5rem !important;
+ box-shadow: 0 12px 24px rgba(0, 0, 0, 0.5) !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-content"] > button[class*="absolute"],
+ [data-theme="ibm"] [role="dialog"] > button[class*="absolute"] {
+ display: none !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-header"] {
+ margin-left: -1.5rem !important;
+ margin-right: -1.5rem !important;
+ margin-top: -1.5rem !important;
+ padding-left: 1.5rem !important;
+ padding-right: 1.5rem !important;
+ padding-top: 1.5rem !important;
+ padding-bottom: 1rem !important;
+ border-bottom: 1px solid #393939 !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-title"] {
+ font-size: 1.25rem !important;
+ font-weight: 400 !important;
+ color: #f4f4f4 !important;
+ }
+ [data-theme="ibm"] [data-slot="dialog-description"] {
+ font-size: 0.875rem !important;
+ color: #c6c6c6 !important;
+ font-weight: 400 !important;
+ margin-top: 0.25rem !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-footer"] {
+ display: grid !important;
+ grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
+ gap: 1px !important;
+ background-color: #262626 !important;
+ margin-left: -1.5rem !important;
+ margin-right: -1.5rem !important;
+ margin-bottom: -1.5rem !important;
+ margin-top: 1rem !important;
+ padding-top: 0 !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-footer"] > button {
+ width: 100% !important;
+ margin: 0 !important;
+ border: 0 !important;
+ border-width: 0 !important;
+ outline: none !important;
+ box-shadow: none !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-footer"] button:first-child {
+ background-color: #6f6f6f !important;
+ color: #ffffff !important;
+ border-radius: 0 !important;
+ height: 4rem !important;
+ font-size: 0.875rem !important;
+ font-weight: 400 !important;
+ justify-content: flex-start !important;
+ align-items: flex-start !important;
+ padding-left: 1rem !important;
+ padding-top: 1rem !important;
+ border: 0 !important;
+ outline: none !important;
+ box-shadow: none !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-footer"] button:first-child:hover {
+ background-color: #525252 !important;
+ border: 0 !important;
+ outline: none !important;
+ box-shadow: none !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-footer"] button:last-child {
+ background-color: #0f62fe !important;
+ color: #ffffff !important;
+ border-radius: 0 !important;
+ height: 4rem !important;
+ font-size: 0.875rem !important;
+ font-weight: 400 !important;
+ justify-content: flex-start !important;
+ align-items: flex-start !important;
+ padding-left: 1rem !important;
+ padding-top: 1rem !important;
+ border: 0 !important;
+ outline: none !important;
+ box-shadow: none !important;
+ }
+
+ [data-theme="ibm"] [data-slot="dialog-footer"] button:last-child:hover {
+ background-color: #0353e9 !important;
+ border: 0 !important;
+ outline: none !important;
+ box-shadow: none !important;
+ }
+
+ [data-theme="ibm"] {
/* Chat (IBM) */
--chat-surface-bg: hsl(var(--background));
--chat-surface-border: hsl(var(--muted));
@@ -262,6 +370,7 @@
--text-text-01: 0 0% 9%;
--link-primary: 217 100% 45%;
--button-tertiary: 217 100% 45%;
+ --brand-amber: 47 89% 53%; /* #f1c21b */
--border-border-interactive: #4589ff;
/* IBM dark grey action button (#393939 → #474747); not --badge (dark badge is #525252) */
--ibm-overwrite-button: 0 0% 22.4%; /* #393939 */
@@ -326,6 +435,7 @@
--accent-pink-foreground: 329 86% 70%;
--accent-purple: 274 66% 32%;
--accent-purple-foreground: 270 95% 75%;
+ --brand-amber: 47 89% 53%; /* #f1c21b */
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 100%;
diff --git a/frontend/app/settings/[tab]/page.tsx b/frontend/app/settings/[tab]/page.tsx
index bc5ec293d..daa701469 100644
--- a/frontend/app/settings/[tab]/page.tsx
+++ b/frontend/app/settings/[tab]/page.tsx
@@ -12,6 +12,7 @@ import { ApiKeysSection } from "../_components/api-keys-section";
import { ConnectorAccessSection } from "../_components/connector-access-section";
import { ConnectorsTab } from "../_components/connectors-tab";
import { IngestSettingsSection } from "../_components/ingest-settings-section";
+import { LangflowUpdatesBanner } from "../_components/langflow-updates-banner";
import ModelProviders from "../_components/model-providers";
const VALID_TABS = [
@@ -143,6 +144,7 @@ export default async function SettingsTabPage({
{tab === "providers" && <ModelProviders />}
{tab === "langflow" && (
<div className="space-y-6">
+ <LangflowUpdatesBanner />
<AgentSettingsSection />
<IngestSettingsSection />
</div>
diff --git a/frontend/app/settings/_components/langflow-updates-banner.tsx b/frontend/app/settings/_components/langflow-updates-banner.tsx
new file mode 100644
index 000000000..12b8c5848
--- /dev/null
+++ b/frontend/app/settings/_components/langflow-updates-banner.tsx
@@ -0,0 +1,93 @@
+"use client";
+
+import { AlertTriangle, X } from "lucide-react";
+import { useState } from "react";
+import { useGetFlowsUpdatesQuery } from "@/app/api/queries/useGetFlowsUpdatesQuery";
+import { FlowsUpdateDialog } from "@/components/flows-update-dialog";
+import { useAuth } from "@/contexts/auth-context";
+import { useBrand } from "@/contexts/brand-context";
+import { usePermissions } from "@/hooks/use-permissions";
+import { cn } from "@/lib/utils";
+
+export function LangflowUpdatesBanner() {
+ const { brand } = useBrand();
+ const isIbm = brand === "ibm";
+ const { runMode } = useAuth();
+ const { can } = usePermissions();
+ const canEdit = can("flows:edit") && runMode === "oss";
+ const { data: updates, isLoading } = useGetFlowsUpdatesQuery({
+ enabled: canEdit,
+ });
+ const [isDismissed, setIsDismissed] = useState(false);
+ const [showModal, setShowModal] = useState(false);
+
+ const undismissedUpdates = updates?.filter((u) => !u.dismissed) ?? [];
+
+ if (
+ !canEdit ||
+ isLoading ||
+ !updates ||
+ undismissedUpdates.length === 0 ||
+ isDismissed
+ ) {
+ return null;
+ }
+
+ return (
+ <>
+ <div
+ className={cn(
+ "mb-6 border border-brand-amber-30 text-foreground px-4 py-3 text-sm",
+ isIbm
+ ? "bg-card border-l-4 border-l-brand-amber rounded-none"
+ : "bg-brand-amber-10 rounded-lg",
+ )}
+ >
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex items-center gap-3 min-w-0">
+ {isIbm ? (
+ <div className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-brand-amber text-card">
+ <span className="font-bold text-xs">!</span>
+ </div>
+ ) : (
+ <AlertTriangle className="h-5 w-5 shrink-0 text-brand-amber" />
+ )}
+ <div className="truncate">
+ <span className="font-semibold text-foreground">
+ Langflow update detected
+ </span>
+ <span className="text-muted-foreground ml-2 hidden sm:inline text-mmd">
+ Modifications to Langflow require an update to revert any custom
+ changes.
+ </span>
+ </div>
+ </div>
+ <div className="flex items-center gap-4 shrink-0">
+ <button
+ type="button"
+ onClick={() => setShowModal(true)}
+ className={cn(
+ "hover:underline font-medium text-sm bg-transparent border-0 cursor-pointer p-0",
+ isIbm ? "text-[#78a9ff]" : "text-primary",
+ )}
+ >
+ View update details
+ </button>
+ <button
+ type="button"
+ onClick={() => setIsDismissed(true)}
+ aria-label="Dismiss banner"
+ className="text-muted-foreground hover:text-foreground bg-transparent border-0 cursor-pointer p-1"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {showModal && (
+ <FlowsUpdateDialog overrideOpen={true} onOpenChange={setShowModal} />
+ )}
+ </>
+ );
+}
diff --git a/frontend/components/flows-update-dialog.tsx b/frontend/components/flows-update-dialog.tsx
new file mode 100644
index 000000000..5a1095ae5
--- /dev/null
+++ b/frontend/components/flows-update-dialog.tsx
@@ -0,0 +1,210 @@
+"use client";
+
+import { AlertCircle } from "lucide-react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { useDismissFlowsUpdateMutation } from "@/app/api/mutations/useDismissFlowsUpdateMutation";
+import { useUpdateFlowsMutation } from "@/app/api/mutations/useUpdateFlowsMutation";
+import { useGetFlowsUpdatesQuery } from "@/app/api/queries/useGetFlowsUpdatesQuery";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { usePermissions } from "@/hooks/use-permissions";
+import { formatFlowName } from "@/lib/utils";
+
+interface FlowsUpdateDialogProps {
+ overrideOpen?: boolean;
+ onOpenChange?: (open: boolean) => void;
+}
+
+export function FlowsUpdateDialog({
+ overrideOpen,
+ onOpenChange,
+}: FlowsUpdateDialogProps = {}) {
+ const { can } = usePermissions();
+ const canEdit = can("flows:edit");
+ const { data: updates, isLoading } = useGetFlowsUpdatesQuery({
+ enabled: canEdit,
+ });
+ const updateMutation = useUpdateFlowsMutation();
+ const dismissMutation = useDismissFlowsUpdateMutation();
+ const [internalIsOpen, setInternalIsOpen] = useState(false);
+ const [showConfirm, setShowConfirm] = useState(false);
+ const [backupCustom, setBackupCustom] = useState(true);
+ const [errorMessage, setErrorMessage] = useState<string | null>(null);
+
+ const isOpen = overrideOpen ?? internalIsOpen;
+ const setIsOpen = (open: boolean) => {
+ setInternalIsOpen(open);
+ onOpenChange?.(open);
+ };
+
+ const undismissedUpdates = updates?.filter((u) => !u.dismissed) ?? [];
+ const hasUndismissed = undismissedUpdates.length > 0;
+
+ const [prevIsLoading, setPrevIsLoading] = useState(isLoading);
+ const [prevHasUndismissed, setPrevHasUndismissed] = useState(hasUndismissed);
+
+ if (isLoading !== prevIsLoading || hasUndismissed !== prevHasUndismissed) {
+ setPrevIsLoading(isLoading);
+ setPrevHasUndismissed(hasUndismissed);
+ if (overrideOpen === undefined) {
+ if (!isLoading && hasUndismissed) {
+ setInternalIsOpen(true);
+ } else if (!isLoading) {
+ setInternalIsOpen(false);
+ }
+ }
+ }
+
+ const handleDismiss = async () => {
+ setIsOpen(false);
+ setShowConfirm(false);
+ if (undismissedUpdates.length === 0) return;
+ try {
+ await dismissMutation.mutateAsync({
+ flow_types: undismissedUpdates.map((u) => u.flow_type),
+ });
+ } catch (e) {
+ console.error("Failed to dismiss flow updates", e);
+ }
+ };
+
+ const handleInitialUpdateClick = () => {
+ setIsOpen(false);
+ setShowConfirm(true);
+ };
+
+ const handleConfirmUpdate = async () => {
+ if (undismissedUpdates.length === 0) return;
+ setErrorMessage(null);
+ const flowTypes = undismissedUpdates.map((u) => u.flow_type);
+
+ try {
+ const results = await updateMutation.mutateAsync({
+ flow_types: flowTypes,
+ backup_custom: backupCustom,
+ });
+
+ const failed = results.filter((r) => !r.success);
+ if (failed.length > 0) {
+ const errorText = failed
+ .map(
+ (f) =>
+ `${formatFlowName(f.flow_type)}: ${f.error || "Update failed"}`,
+ )
+ .join("; ");
+ setErrorMessage(errorText);
+ toast.error(`Flow update failed: ${errorText}`);
+ } else {
+ toast.success("Flows updated successfully");
+ setShowConfirm(false);
+ }
+ } catch (e: any) {
+ const msg = e?.message || "Failed to update flows";
+ setErrorMessage(msg);
+ toast.error(msg);
+ }
+ };
+
+ if (
+ !can("flows:edit") ||
+ (overrideOpen === undefined && undismissedUpdates.length === 0)
+ )
+ return null;
+
+ return (
+ <>
+ <Dialog open={isOpen} onOpenChange={setIsOpen}>
+ <DialogContent className="sm:max-w-[540px]">
+ <DialogHeader>
+ <DialogTitle>Update required from Langflow</DialogTitle>
+ <DialogDescription>
+ OpenRAG will back up your customized flows first
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 py-2">
+ {errorMessage && (
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Update Failed</AlertTitle>
+ <AlertDescription>{errorMessage}</AlertDescription>
+ </Alert>
+ )}
+
+ <p className="text-sm text-muted-foreground leading-relaxed">
+ Updating Langflow discards your customizations to OpenRAG flows.
+ OpenRAG copies the core flows before updating, so you can reapply
+ your changes afterward. OpenRAG stores the copies in its embedded
+ Langflow instance.
+ </p>
+
+ <div className="flex items-center space-x-2 pt-2">
+ <Checkbox
+ id="backup-custom"
+ checked={backupCustom}
+ onCheckedChange={(checked) => setBackupCustom(!!checked)}
+ />
+ <label
+ htmlFor="backup-custom"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Back up my flows in Langflow before updating
+ </label>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={handleDismiss}>
+ Skip action
+ </Button>
+ <Button onClick={handleInitialUpdateClick}>Update flow</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog open={showConfirm} onOpenChange={setShowConfirm}>
+ <DialogContent className="sm:max-w-[540px]">
+ <DialogHeader>
+ <DialogTitle>Confirm Langflow Update</DialogTitle>
+ </DialogHeader>
+
+ <div className="py-2">
+ <p className="text-sm text-muted-foreground leading-relaxed">
+ Updating Langflow will overwrite any custom changes made. Backup
+ copies of your flows will be created in Langflow. Do you want to
+ continue?
+ </p>
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => {
+ setShowConfirm(false);
+ setIsOpen(true);
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={handleConfirmUpdate}
+ disabled={updateMutation.isPending}
+ >
+ {updateMutation.isPending ? "Updating..." : "Continue update"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/frontend/components/layout-wrapper.tsx b/frontend/components/layout-wrapper.tsx
index 58aa9e453..f31097c18 100644
--- a/frontend/components/layout-wrapper.tsx
+++ b/frontend/components/layout-wrapper.tsx
@@ -25,6 +25,7 @@ import { isFailureLikeTask } from "@/lib/task-utils";
import { cn } from "@/lib/utils";
import { AnimatedConditional } from "./animated-conditional";
import { ChatRenderer } from "./chat-renderer";
+import { FlowsUpdateDialog } from "./flows-update-dialog";
import { Header } from "./header";
import FailedTasksInfo from "./tasks_details";
@@ -45,7 +46,8 @@ export function LayoutWrapper({ children }: { children: React.ReactNode }) {
}
}, [isMenuOpen, closePanelOnly]);
- const { isLoading, isAuthenticated, isNoAuthMode, isIbmAuthMode } = useAuth();
+ const { isLoading, isAuthenticated, isNoAuthMode, isIbmAuthMode, runMode } =
+ useAuth();
const { isOnboardingComplete } = useChat();
const authPaths = ["/login", "/auth/callback", "/unauthorized"];
@@ -184,6 +186,10 @@ export function LayoutWrapper({ children }: { children: React.ReactNode }) {
</div>
</div>
</div>
+
+ {(isAuthenticated || isNoAuthMode) && runMode === "oss" && (
+ <FlowsUpdateDialog />
+ )}
</div>
);
}
diff --git a/frontend/components/ui/alert.tsx b/frontend/components/ui/alert.tsx
index 4b22d3199..d3db05e48 100644
--- a/frontend/components/ui/alert.tsx
+++ b/frontend/components/ui/alert.tsx
@@ -55,7 +55,7 @@ function AlertDescription({
<div
data-slot="alert-description"
className={cn(
- "text-sm text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
+ "text-sm text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4 group-has-[>svg]/alert:col-start-2",
className,
)}
{...props}
diff --git a/frontend/components/ui/checkbox.tsx b/frontend/components/ui/checkbox.tsx
new file mode 100644
index 000000000..212c7b8ee
--- /dev/null
+++ b/frontend/components/ui/checkbox.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
+import { Check } from "lucide-react";
+import * as React from "react";
+import { cn } from "@/lib/utils";
+
+const Checkbox = React.forwardRef<
+ React.ElementRef<typeof CheckboxPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <CheckboxPrimitive.Root
+ ref={ref}
+ className={cn(
+ "grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
+ className,
+ )}
+ {...props}
+ >
+ <CheckboxPrimitive.Indicator
+ className={cn("grid place-content-center text-current")}
+ >
+ <Check className="h-4 w-4" />
+ </CheckboxPrimitive.Indicator>
+ </CheckboxPrimitive.Root>
+));
+Checkbox.displayName = CheckboxPrimitive.Root.displayName;
+
+export { Checkbox };
diff --git a/frontend/components/ui/dialog.tsx b/frontend/components/ui/dialog.tsx
index af4b983f4..b9d728830 100644
--- a/frontend/components/ui/dialog.tsx
+++ b/frontend/components/ui/dialog.tsx
@@ -42,6 +42,7 @@ function DialogContent({
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
+ data-slot="dialog-content"
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
@@ -63,6 +64,7 @@ const DialogHeader = ({
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
+ data-slot="dialog-header"
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className,
@@ -76,6 +78,7 @@ const DialogFooter = ({
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
+ data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className,
@@ -92,6 +95,7 @@ function DialogTitle({
return (
<DialogPrimitive.Title
ref={ref}
+ data-slot="dialog-title"
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className,
@@ -109,6 +113,7 @@ function DialogDescription({
return (
<DialogPrimitive.Description
ref={ref}
+ data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
diff --git a/frontend/lib/utils.ts b/frontend/lib/utils.ts
index 6c77be3b5..64a6945b9 100644
--- a/frontend/lib/utils.ts
+++ b/frontend/lib/utils.ts
@@ -20,3 +20,8 @@ export function encodeBase64(str: string): string {
export function decodeBase64(str: string): string {
return Buffer.from(str, "base64").toString("utf-8");
}
+
+export function formatFlowName(type: string): string {
+ if (type === "url_ingest") return "URL Ingest";
+ return type.charAt(0).toUpperCase() + type.slice(1).replace(/_/g, " ");
+}
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index bdcf11119..c8ab7bcb7 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -10,6 +10,7 @@
"dependencies": {
"@radix-ui/react-accordion": "^1.2.14",
"@radix-ui/react-avatar": "^1.2.0",
+ "@radix-ui/react-checkbox": "^1.3.9",
"@radix-ui/react-collapsible": "^1.1.14",
"@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dropdown-menu": "^2.1.18",
@@ -1348,6 +1349,207 @@
}
}
},
+ "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==",
+ "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"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/primitive": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.7.tgz",
+ "integrity": "sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q==",
+ "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==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-use-layout-effect": "1.1.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-slot": "1.3.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.4"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "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"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-use-layout-effect": "1.1.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "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==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-use-layout-effect": "1.1.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-collapsible": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.14.tgz",
@@ -1475,6 +1677,10 @@
"resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.2.tgz",
"integrity": "sha512-C3vFhbyi4SW3PmbAi6Awpu4OzJtd0MxGurvSsYtr7p7nM8RNB3VAF3CUmnp2j50knpkrRcB7+ycVXzgLgF6yNA==",
"license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-use-effect-event": "0.0.3",
+ "@radix-ui/react-use-layout-effect": "1.1.2"
+ },
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
@@ -1499,16 +1705,11 @@
},
"peerDependencies": {
"@types/react": "*",
- "@types/react-dom": "*",
- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
- "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
- },
- "@types/react-dom": {
- "optional": true
}
}
},
@@ -1528,16 +1729,11 @@
},
"peerDependencies": {
"@types/react": "*",
- "@types/react-dom": "*",
- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
- "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
- },
- "@types/react-dom": {
- "optional": true
}
}
},
@@ -1609,16 +1805,11 @@
},
"peerDependencies": {
"@types/react": "*",
- "@types/react-dom": "*",
- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
- "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
- },
- "@types/react-dom": {
- "optional": true
}
}
},
diff --git a/frontend/package.json b/frontend/package.json
index 223eaa014..90b74328e 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -19,6 +19,7 @@
"dependencies": {
"@radix-ui/react-accordion": "^1.2.14",
"@radix-ui/react-avatar": "^1.2.0",
+ "@radix-ui/react-checkbox": "^1.3.9",
"@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/src/api/flows.py b/src/api/flows.py
index c9f2f666a..b65de9a73 100644
--- a/src/api/flows.py
+++ b/src/api/flows.py
@@ -1,18 +1,26 @@
"""Reset Flow API endpoints"""
+
from typing import Literal
from fastapi import Depends
from fastapi.responses import JSONResponse
-from utils.logging_config import get_logger
+from pydantic import BaseModel
-from dependencies import get_flows_service, get_current_user, require_permission
+from dependencies import get_flows_service, require_permission
from session_manager import User
+from utils.logging_config import get_logger
logger = get_logger(__name__)
FlowType = Literal["nudges", "retrieval", "ingest"]
+def _is_oss_mode() -> bool:
+ from config.settings import IBM_AUTH_ENABLED, is_dev_ibm_cos_enabled
+
+ return not (IBM_AUTH_ENABLED or is_dev_ibm_cos_enabled())
+
+
async def reset_flow_endpoint(
flow_type: str,
flows_service=Depends(get_flows_service),
@@ -23,27 +31,19 @@ async def reset_flow_endpoint(
return JSONResponse(
{
"success": False,
- "error": "Invalid flow type. Must be 'nudges', 'retrieval', or 'ingest'"
+ "error": "Invalid flow type. Must be 'nudges', 'retrieval', or 'ingest'",
},
- status_code=400
+ status_code=400,
)
try:
result = await flows_service.reset_langflow_flow(flow_type)
if result.get("success"):
- logger.info(
- "Flow reset successful",
- flow_type=flow_type,
- flow_id=result.get("flow_id")
- )
+ logger.info("Flow reset successful", flow_type=flow_type, flow_id=result.get("flow_id"))
return JSONResponse(result, status_code=200)
else:
- logger.error(
- "Flow reset failed",
- flow_type=flow_type,
- error=result.get("error")
- )
+ logger.error("Flow reset failed", flow_type=flow_type, error=result.get("error"))
return JSONResponse(result, status_code=500)
except ValueError as e:
@@ -51,7 +51,67 @@ async def reset_flow_endpoint(
return JSONResponse({"success": False, "error": str(e)}, status_code=400)
except Exception as e:
logger.error("Unexpected error in flow reset", error=str(e))
+ return JSONResponse({"success": False, "error": "Internal server error"}, status_code=500)
+
+
+class BulkUpdateFlowsRequest(BaseModel):
+ flow_types: list[str]
+ backup_custom: bool = True
+
+
+async def get_flows_updates_endpoint(
+ flows_service=Depends(get_flows_service),
+ user: User = Depends(require_permission("flows:read")),
+):
+ """Get available updates for core flows"""
+ if not _is_oss_mode():
+ return JSONResponse({"success": True, "updates": []}, status_code=200)
+ try:
+ user_id = getattr(user, "db_user_id", None) or getattr(user, "user_id", None)
+ updates = await flows_service.get_flows_updates_available(user_id=user_id)
+ return JSONResponse({"success": True, "updates": updates}, status_code=200)
+ except Exception as e:
+ logger.error("Error getting flow updates", error=str(e))
+ return JSONResponse({"success": False, "error": "Internal server error"}, status_code=500)
+
+
+async def bulk_update_flows_endpoint(
+ request: BulkUpdateFlowsRequest,
+ flows_service=Depends(get_flows_service),
+ user: User = Depends(require_permission("flows:edit")),
+):
+ """Bulk update multiple flows and optionally backup custom flows"""
+ if not _is_oss_mode():
return JSONResponse(
- {"success": False, "error": f"Internal server error: {str(e)}"},
- status_code=500
+ {"success": False, "error": "Flow updates are only available in OSS mode"},
+ status_code=403,
)
+ try:
+ results = await flows_service.bulk_update_flows(request.flow_types, request.backup_custom)
+ overall_success = all(r.get("success", False) for r in results)
+ return JSONResponse({"success": overall_success, "results": results}, status_code=200)
+ except Exception as e:
+ logger.error("Error bulk updating flows", error=str(e))
+ return JSONResponse({"success": False, "error": "Internal server error"}, status_code=500)
+
+
+class DismissFlowsUpdateRequest(BaseModel):
+ flow_types: list[str] | None = None
+
+
+async def dismiss_flows_update_endpoint(
+ request: DismissFlowsUpdateRequest | None = None,
+ flows_service=Depends(get_flows_service),
+ user: User = Depends(require_permission("flows:read")),
+):
+ """Dismiss available flow update notifications ephemerally in backend memory"""
+ if not _is_oss_mode():
+ return JSONResponse({"success": True}, status_code=200)
+ try:
+ flow_types = request.flow_types if request else None
+ user_id = getattr(user, "db_user_id", None) or getattr(user, "user_id", None)
+ flows_service.dismiss_flows_updates(flow_types, user_id=user_id)
+ return JSONResponse({"success": True}, status_code=200)
+ except Exception as e:
+ logger.error("Error dismissing flow updates", error=str(e))
+ return JSONResponse({"success": False, "error": "Internal server error"}, status_code=500)
diff --git a/src/app/routes/internal.py b/src/app/routes/internal.py
index 886a1defe..25e2492b1 100644
--- a/src/app/routes/internal.py
+++ b/src/app/routes/internal.py
@@ -426,6 +426,26 @@ def register_internal_routes(app: FastAPI):
tags=["internal"],
)
+ # Flow updates endpoints
+ app.add_api_route(
+ "/settings/flows/updates-available",
+ flows.get_flows_updates_endpoint,
+ methods=["GET"],
+ tags=["internal"],
+ )
+ app.add_api_route(
+ "/settings/flows/update",
+ flows.bulk_update_flows_endpoint,
+ methods=["POST"],
+ tags=["internal"],
+ )
+ app.add_api_route(
+ "/settings/flows/dismiss-update",
+ flows.dismiss_flows_update_endpoint,
+ methods=["POST"],
+ tags=["internal"],
+ )
+
# Router upload ingest endpoint
app.add_api_route(
"/router/upload_ingest",
diff --git a/src/services/flows_service.py b/src/services/flows_service.py
index f596d2822..bb2cbe1a6 100644
--- a/src/services/flows_service.py
+++ b/src/services/flows_service.py
@@ -1,7 +1,7 @@
import asyncio
import json
import os
-from datetime import datetime
+from datetime import UTC, datetime
from typing import Any
from cachetools import LRUCache
@@ -25,6 +25,48 @@ logger = get_logger(__name__)
class FlowsService:
+ def __init__(self) -> None:
+ # Ephemeral dict of dismissed flow update notifications per user_id
+ self._dismissed_updates: dict[str, set[str]] = {}
+ # Cache for flow file mappings to avoid repeated filesystem scans
+ self._flow_file_cache: dict[str, str] = {}
+ # Semaphores to prevent race conditions when updating the same flow concurrently
+ self._flow_locks = LRUCache(maxsize=128)
+ self._lock_creation_lock = asyncio.Lock()
+ # Cache for enabled models to avoid redundant API calls
+ self._enabled_models_cache: dict[str, Any] | None = None
+ self._enabled_models_cache_time: datetime | None = None
+ self._enabled_models_cache_ttl = 60 # seconds
+ self._enabled_models_lock = asyncio.Lock()
+ # Cache for available custom flow updates
+ self._custom_updates_cache: list[dict[str, Any]] | None = None
+
+ def dismiss_flows_updates(
+ self, flow_types: list[str] | None = None, user_id: str | None = None
+ ) -> None:
+ """Dismiss flow update notifications ephemerally in backend memory per user."""
+ if not hasattr(self, "_dismissed_updates") or not isinstance(self._dismissed_updates, dict):
+ self._dismissed_updates = {}
+ target_user = user_id or "default"
+ if target_user not in self._dismissed_updates:
+ self._dismissed_updates[target_user] = set()
+
+ if flow_types:
+ self._dismissed_updates[target_user].update(flow_types)
+ else:
+ self._dismissed_updates[target_user].update(
+ ["nudges", "retrieval", "ingest", "url_ingest"]
+ )
+
+ def clear_dismissed_update(self, flow_type: str, user_id: str | None = None):
+ if hasattr(self, "_dismissed_updates") and isinstance(self._dismissed_updates, dict):
+ if user_id:
+ if user_id in self._dismissed_updates:
+ self._dismissed_updates[user_id].discard(flow_type)
+ else:
+ for user_set in self._dismissed_updates.values():
+ user_set.discard(flow_type)
+
async def resolve_ollama_url(self, endpoint: str, force_refresh: bool = False) -> str:
"""Find the correct Ollama URL by probing candidates via Langflow's validate-provider API."""
from config.config_manager import config_manager
@@ -87,18 +129,6 @@ class FlowsService:
return resolved_url
- def __init__(self):
- # Cache for flow file mappings to avoid repeated filesystem scans
- self._flow_file_cache = {}
- # Semaphores to prevent race conditions when updating the same flow concurrently
- self._flow_locks = LRUCache(maxsize=128)
- self._lock_creation_lock = asyncio.Lock()
- # Cache for enabled models to avoid redundant API calls
- self._enabled_models_cache = None
- self._enabled_models_cache_time = None
- self._enabled_models_cache_ttl = 60 # seconds
- self._enabled_models_lock = asyncio.Lock()
-
async def _get_flow_lock(self, flow_id: str) -> asyncio.Lock:
"""Get or create an asyncio.Lock for a specific flow ID"""
async with self._lock_creation_lock:
@@ -305,8 +335,12 @@ class FlowsService:
for result in results:
if not result:
continue
- backup_results[result["type"]].append(result["data"])
- if result["type"] == "failed":
+ res_type = result.get("type")
+ if res_type in ("backed_up", "skipped", "failed"):
+ target_list = backup_results[res_type]
+ if isinstance(target_list, list):
+ target_list.append(result.get("data"))
+ if res_type == "failed":
backup_results["success"] = False
logger.info(
@@ -328,7 +362,7 @@ class FlowsService:
return backup_results
- async def _backup_flow(self, flow_id: str, flow_type: str, flow_data: dict = None):
+ async def _backup_flow(self, flow_id: str, flow_type: str, flow_data: dict | None = None):
"""
Backup a single flow to the backup folder.
@@ -435,19 +469,7 @@ class FlowsService:
logger.warning(f"Flow with ID {flow_id} not found in flows directory")
return None
- async def reset_langflow_flow(self, flow_type: str):
- """Reset a Langflow flow by uploading the corresponding JSON file
-
- Args:
- flow_type: Either 'nudges', 'retrieval', or 'ingest'
-
- Returns:
- dict: Success/error response
- """
- if not LANGFLOW_URL:
- raise ValueError("LANGFLOW_URL environment variable is required")
-
- # Determine flow ID based on type
+ def _get_flow_id_by_type(self, flow_type: str) -> str:
if flow_type == "nudges":
flow_id = NUDGES_FLOW_ID
elif flow_type == "retrieval":
@@ -460,9 +482,64 @@ class FlowsService:
raise ValueError(
"flow_type must be either 'nudges', 'retrieval', 'ingest', or 'url_ingest'"
)
-
if not flow_id:
raise ValueError(f"Flow ID not configured for flow_type '{flow_type}'")
+ return flow_id
+
+ async def reset_langflow_flow(self, flow_type: str):
+ """Reset a Langflow flow by uploading the corresponding JSON file
+
+ Args:
+ flow_type: Either 'nudges', 'retrieval', 'ingest', or 'url_ingest'
+
+ Returns:
+ dict: Success/error response
+ """
+ flow_id = self._get_flow_id_by_type(flow_type)
+ flow_lock = await self._get_flow_lock(flow_id)
+ async with flow_lock:
+ result = await self._reset_langflow_flow_locked(flow_type, flow_id)
+ if result.get("success"):
+ self._custom_updates_cache = None
+ try:
+ config = get_openrag_config()
+ if config.edited:
+ from api.settings import reapply_all_settings
+
+ await reapply_all_settings()
+ except Exception as e:
+ logger.error(f"Error reapplying settings after flow reset: {e}")
+ return result
+
+ async def _unlock_flow(self, flow_id: str):
+ """Unlock a flow before making changes."""
+ try:
+ response = await clients.langflow_request(
+ "PATCH", f"/api/v1/flows/{flow_id}", json={"locked": False}
+ )
+ if response.status_code not in (200, 404):
+ logger.warning(
+ f"Failed to unlock flow {flow_id}: HTTP {response.status_code} - {response.text}"
+ )
+ except Exception as e:
+ logger.warning(f"Error unlocking flow {flow_id}: {e}")
+
+ async def _lock_flow(self, flow_id: str):
+ """Lock a flow after making changes."""
+ try:
+ response = await clients.langflow_request(
+ "PATCH", f"/api/v1/flows/{flow_id}", json={"locked": True}
+ )
+ if response.status_code not in (200, 404):
+ logger.warning(
+ f"Failed to lock flow {flow_id}: HTTP {response.status_code} - {response.text}"
+ )
+ except Exception as e:
+ logger.warning(f"Error locking flow {flow_id}: {e}")
+
+ async def _reset_langflow_flow_locked(self, flow_type: str, flow_id: str):
+ if not LANGFLOW_URL:
+ raise ValueError("LANGFLOW_URL environment variable is required")
# Dynamically find the flow file by ID
flow_path = self._find_flow_file_by_id(flow_id)
@@ -481,6 +558,8 @@ class FlowsService:
except FileNotFoundError as e:
raise ValueError(f"Flow file not found: {flow_path}") from e
+ await self._unlock_flow(flow_id)
+
# Make PATCH request to Langflow API to update the flow using shared client
try:
response = await clients.langflow_request(
@@ -488,73 +567,12 @@ class FlowsService:
)
if response.status_code == 200:
+ await self._lock_flow(flow_id)
logger.info(
f"Successfully reset {flow_type} flow",
flow_id=flow_id,
flow_file=os.path.basename(flow_path),
)
-
- # Now update the flow with current configuration settings
- try:
- config = get_openrag_config()
-
- # Check if configuration has been edited (onboarding completed)
- if config.edited:
- logger.info(
- f"Updating {flow_type} flow with current configuration settings"
- )
-
- # Update current LLM provider
- update_result = await self._update_provider_components(
- {"name": flow_type, "flow_id": flow_id},
- config.agent.llm_provider.lower(),
- llm_model=config.agent.llm_model,
- force_llm_update=True,
- )
-
- # Update all configured embedding providers
- embedding_providers = []
- if config.providers.openai.configured:
- embedding_providers.append("openai")
- if config.providers.watsonx.configured:
- embedding_providers.append("watsonx")
- if config.providers.ollama.configured:
- embedding_providers.append("ollama")
-
- current_emb_provider = config.knowledge.embedding_provider.lower()
- for provider in embedding_providers:
- model = (
- config.knowledge.embedding_model
- if provider == current_emb_provider
- else None
- )
- await self._update_provider_components(
- {"name": flow_type, "flow_id": flow_id},
- provider,
- embedding_model=model,
- force_embedding_update=True,
- )
-
- if update_result.get("success"):
- logger.info(
- f"Successfully updated {flow_type} flow with current configuration"
- )
- else:
- logger.warning(
- f"Failed to update {flow_type} flow with current configuration: {update_result.get('error', 'Unknown error')}"
- )
- else:
- logger.info(
- f"Configuration not yet edited (onboarding not completed), skipping model updates for {flow_type} flow"
- )
-
- except Exception as e:
- logger.error(
- f"Error updating {flow_type} flow with current configuration",
- error=str(e),
- )
- # Don't fail the entire reset operation if configuration update fails
-
return {
"success": True,
"message": f"Successfully reset {flow_type} flow",
@@ -627,7 +645,7 @@ class FlowsService:
return "OpenAI"
async def _update_flow_field(
- self, flow_id: str, field_name: str, field_value: Any, node_display_name: str = None
+ self, flow_id: str, field_name: str, field_value: Any, node_display_name: str | None = None
):
"""
Generic helper function to update any field in any Langflow component.
@@ -684,6 +702,8 @@ class FlowsService:
identifier = node_display_name
raise Exception(f"{field_name} field not found in {identifier} component")
+ await self._unlock_flow(flow_id)
+
# Update the flow via PATCH request
patch_response = await clients.langflow_request(
"PATCH", f"/api/v1/flows/{flow_id}", json=flow_data
@@ -694,6 +714,8 @@ class FlowsService:
f"Failed to update flow: HTTP {patch_response.status_code} - {patch_response.text}"
)
+ await self._lock_flow(flow_id)
+
async def update_chat_flow_system_prompt(self, system_prompt: str):
"""Helper function to update the system prompt in the chat flow"""
if not LANGFLOW_CHAT_FLOW_ID:
@@ -742,20 +764,34 @@ class FlowsService:
node_display_name="Split Text",
)
- def _normalize_flow_structure(self, flow_data):
+ def _normalize_flow_structure(self, flow_data: dict[str, Any]) -> dict[str, Any]:
"""
Normalize flow structure for comparison by removing dynamic fields.
- Keeps structural elements: nodes (types, display names, templates), edges (connections).
- Removes: IDs, timestamps, positions, etc. but keeps template structure.
+ Keeps structural elements: nodes (types, display names, template definitions), edges (connections).
+ Removes: IDs, timestamps, positions, dynamic runtime field values, and dynamic options lists.
"""
- normalized = {"data": {"nodes": [], "edges": []}}
+ normalized: dict[str, Any] = {"data": {"nodes": [], "edges": []}}
- # Normalize nodes - keep structural info including templates
+ # Normalize nodes - keep structural info including template definitions
nodes = flow_data.get("data", {}).get("nodes", [])
for node in nodes:
node_data = node.get("data", {})
node_template = node_data.get("node", {})
+ template = node_template.get("template", {})
+ normalized_template: dict[str, Any] = {}
+ if isinstance(template, dict):
+ for field_name, field_def in template.items():
+ if isinstance(field_def, dict):
+ normalized_template[field_name] = {
+ "type": field_def.get("type"),
+ "display_name": field_def.get("display_name"),
+ "required": field_def.get("required"),
+ "input_types": field_def.get("input_types"),
+ }
+ else:
+ normalized_template[field_name] = {"value": str(field_def)}
+
normalized_node = {
"id": node.get("id"), # Keep ID for edge matching
"type": node.get("type"),
@@ -764,7 +800,7 @@ class FlowsService:
"display_name": node_template.get("display_name"),
"name": node_template.get("name"),
"base_classes": node_template.get("base_classes", []),
- "template": node_template.get("template", {}), # Include template structure
+ "template": normalized_template,
}
},
}
@@ -783,70 +819,51 @@ class FlowsService:
return normalized
- async def _compare_flow_with_file(self, flow_id: str):
+ async def _check_flow_update(
+ self, flow_type: str, flow_id: str, flow_data: dict[str, Any] | None = None
+ ) -> dict[str, Any] | None:
"""
- Compare a Langflow flow with its JSON file.
- Returns True if flows match (indicating a reset), False otherwise.
+ Check if a flow has a newer version on disk compared to Langflow.
+ Returns flow update info dict if an update is available, None otherwise.
"""
- try:
- # Get flow from Langflow API
- response = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")
- if response.status_code != 200:
- logger.warning(
- f"Failed to get flow {flow_id} from Langflow: HTTP {response.status_code}"
- )
- return False
-
- langflow_flow = response.json()
-
- # Find and load the corresponding JSON file
- flow_path = self._find_flow_file_by_id(flow_id)
- if not flow_path:
- logger.warning(f"Flow file not found for flow ID: {flow_id}")
- return False
-
- with open(flow_path) as f:
- file_flow = json.load(f)
-
- # Normalize both flows for comparison
- normalized_langflow = self._normalize_flow_structure(langflow_flow)
- normalized_file = self._normalize_flow_structure(file_flow)
-
- # Compare entire normalized structures exactly
- # Sort nodes and edges for consistent comparison
- normalized_langflow["data"]["nodes"] = sorted(
- normalized_langflow["data"]["nodes"],
- key=lambda x: (x.get("id", ""), x.get("type", "")),
- )
- normalized_file["data"]["nodes"] = sorted(
- normalized_file["data"]["nodes"], key=lambda x: (x.get("id", ""), x.get("type", ""))
- )
-
- normalized_langflow["data"]["edges"] = sorted(
- normalized_langflow["data"]["edges"],
- key=lambda x: (
- x.get("source", ""),
- x.get("target", ""),
- x.get("sourceHandle", ""),
- x.get("targetHandle", ""),
- ),
- )
- normalized_file["data"]["edges"] = sorted(
- normalized_file["data"]["edges"],
- key=lambda x: (
- x.get("source", ""),
- x.get("target", ""),
- x.get("sourceHandle", ""),
- x.get("targetHandle", ""),
- ),
- )
+ if not flow_id:
+ return None
+ flow_path = self._find_flow_file_by_id(flow_id)
+ if not flow_path or not os.path.exists(flow_path):
+ return None
+ local_mtime = os.path.getmtime(flow_path)
- # Compare entire normalized structures
- return normalized_langflow == normalized_file
+ if flow_data is None:
+ try:
+ response = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")
+ if response.status_code != 200:
+ return None
+ flow_data = response.json()
+ except Exception as e:
+ logger.error(f"Failed to fetch flow {flow_id} for update check: {e}")
+ return None
- except Exception as e:
- logger.error(f"Error comparing flow {flow_id} with file: {str(e)}")
- return False
+ langflow_updated_at_str = flow_data.get("updated_at")
+ langflow_mtime: float = 0.0
+ if langflow_updated_at_str:
+ if langflow_updated_at_str.endswith("Z"):
+ langflow_updated_at_str = langflow_updated_at_str[:-1] + "+00:00"
+ try:
+ dt = datetime.fromisoformat(langflow_updated_at_str)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=UTC)
+ langflow_mtime = dt.timestamp()
+ except ValueError:
+ pass
+
+ if local_mtime > langflow_mtime + 1.0:
+ is_locked = flow_data.get("locked", False)
+ return {
+ "flow_type": flow_type,
+ "flow_id": flow_id,
+ "is_custom": not is_locked,
+ }
+ return None
async def ensure_flows_exist(self) -> set[str]:
"""
@@ -857,9 +874,6 @@ class FlowsService:
patches or overwrites an existing flow, preserving any edits the user
has made in the Langflow UI.
- This replaces the LANGFLOW_LOAD_FLOWS_PATH mechanism, which performed a
- blind upsert on every container start and discarded user edits.
-
Returns the set of flow type names that were actually created.
"""
flow_configs = [
@@ -919,47 +933,31 @@ class FlowsService:
tasks = [ensure_single_flow_exists(ft, fi) for ft, fi in flow_configs]
results = await asyncio.gather(*tasks)
created_flow_types = {r for r in results if r is not None}
- return created_flow_types
- async def check_flows_reset(self):
- """
- Check if any flows have been reset by comparing with JSON files.
- Returns list of flow types that were reset.
- """
- reset_flows = []
-
- flow_configs = [
- ("nudges", NUDGES_FLOW_ID),
- ("retrieval", LANGFLOW_CHAT_FLOW_ID),
- ("ingest", LANGFLOW_INGEST_FLOW_ID),
- ("url_ingest", LANGFLOW_URL_INGEST_FLOW_ID),
- ]
+ if created_flow_types:
+ try:
+ config = get_openrag_config()
+ if config.edited:
+ logger.info(
+ f"Newly created flows detected ({', '.join(created_flow_types)}), reapplying settings."
+ )
+ from api.settings import reapply_all_settings
- async def check_single_flow_reset(flow_type, flow_id):
- if not flow_id:
- return None
- logger.info(f"Checking if {flow_type} flow (ID: {flow_id}) was reset")
- is_reset = await self._compare_flow_with_file(flow_id)
- if is_reset:
- logger.info(f"Flow {flow_type} (ID: {flow_id}) appears to have been reset")
- return flow_type
- else:
- logger.info(f"Flow {flow_type} (ID: {flow_id}) does not match reset state")
- return None
+ await reapply_all_settings()
+ logger.info("Successfully reapplied settings for newly created flows")
+ except Exception as e:
+ logger.error(f"Failed to reapply settings for newly created flows: {e}")
- tasks = [check_single_flow_reset(ft, fi) for ft, fi in flow_configs]
- results = await asyncio.gather(*tasks)
- reset_flows = [r for r in results if r is not None]
- return reset_flows
+ return created_flow_types
async def change_langflow_model_value(
self,
provider: str,
- embedding_model: str = None,
- llm_model: str = None,
+ embedding_model: str | None = None,
+ llm_model: str | None = None,
force_embedding_update: bool = False,
force_llm_update: bool = False,
- flow_configs: list = None,
+ flow_configs: list | None = None,
):
"""
Change dropdown values for provider-specific components across flows
@@ -1020,35 +1018,55 @@ class FlowsService:
async def _update_provider_components(
self,
- config,
- provider: str,
- embedding_model: str = None,
- llm_model: str = None,
+ config: dict,
+ provider_name: str,
+ embedding_model: str | None = None,
+ llm_model: str | None = None,
force_embedding_update: bool = False,
force_llm_update: bool = False,
):
"""Update provider components and their dropdown values in a flow"""
- flow_name = config["name"]
flow_id = config["flow_id"]
- # Use a flow-specific lock to prevent race conditions during the GET-Modify-PATCH cycle
flow_lock = await self._get_flow_lock(flow_id)
async with flow_lock:
- # Get flow data from Langflow API instead of file
- response = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")
+ return await self._update_provider_components_locked(
+ config,
+ provider_name,
+ embedding_model=embedding_model,
+ llm_model=llm_model,
+ force_embedding_update=force_embedding_update,
+ force_llm_update=force_llm_update,
+ )
- if response.status_code != 200:
- raise Exception(
- f"Failed to get flow from Langflow: HTTP {response.status_code} - {response.text}"
- )
+ async def _update_provider_components_locked(
+ self,
+ config: dict,
+ provider_name: str,
+ embedding_model: str | None = None,
+ llm_model: str | None = None,
+ force_embedding_update: bool = False,
+ force_llm_update: bool = False,
+ ):
+ """Internal helper to update provider components when flow_lock is already held"""
+ flow_name = config["name"]
+ flow_id = config["flow_id"]
+ # Get flow data from Langflow API instead of file
+ response = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")
- flow_data = response.json()
- updates_made = []
- node_tasks = []
+ if response.status_code != 200:
+ raise Exception(
+ f"Failed to get flow from Langflow: HTTP {response.status_code} - {response.text}"
+ )
- async def wrap_node_update(node, p, m, label):
- if await self._update_component_fields(node, p, m):
- return label
- return None
+ flow_data = response.json()
+ provider = provider_name
+ updates_made = []
+ node_tasks: list[Any] = []
+
+ async def wrap_node_update(node, p, m, label):
+ if await self._update_component_fields(node, p, m):
+ return label
+ return None
# Get all embedding nodes in the flow to check if flow is new (no 3 embeddings)
embedding_nodes = self._find_nodes_in_flow(
@@ -1194,39 +1212,41 @@ class FlowsService:
)
)
- # Execute all node updates simultaneously
- if node_tasks:
- node_results = await asyncio.gather(*node_tasks)
- updates_made.extend([r for r in node_results if r])
-
- # If no updates were made, return skip message
- if not updates_made:
- return {
- "flow": flow_name,
- "success": True,
- "message": f"No compatible components found in {flow_name} flow (skipped)",
- "flow_id": flow_id,
- }
-
- logger.info(f"Updated {', '.join(updates_made)} in {flow_name} flow")
-
- # PATCH the updated flow
- response = await clients.langflow_request(
- "PATCH", f"/api/v1/flows/{flow_id}", json=flow_data
- )
-
- if response.status_code != 200:
- raise Exception(
- f"Failed to update flow: HTTP {response.status_code} - {response.text}"
- )
+ # Execute all node updates simultaneously
+ if node_tasks:
+ node_results = await asyncio.gather(*node_tasks)
+ updates_made.extend([r for r in node_results if r])
+ # If no updates were made, return skip message
+ if not updates_made:
return {
"flow": flow_name,
"success": True,
- "message": f"Successfully updated {', '.join(updates_made)}",
+ "message": f"No compatible components found in {flow_name} flow (skipped)",
"flow_id": flow_id,
}
+ logger.info(f"Updated {', '.join(updates_made)} in {flow_name} flow")
+
+ await self._unlock_flow(flow_id)
+
+ # PATCH the updated flow
+ response = await clients.langflow_request(
+ "PATCH", f"/api/v1/flows/{flow_id}", json=flow_data
+ )
+
+ if response.status_code != 200:
+ raise Exception(f"Failed to update flow: HTTP {response.status_code} - {response.text}")
+
+ await self._lock_flow(flow_id)
+
+ return {
+ "flow": flow_name,
+ "success": True,
+ "message": f"Successfully updated {', '.join(updates_made)}",
+ "flow_id": flow_id,
+ }
+
async def _update_component_langflow(self, template, model: Any):
# Call custom_component/update endpoint to get updated template
# Only call if code field exists (custom components should have code)
@@ -1435,3 +1455,174 @@ class FlowsService:
elif provider == "anthropic":
return (None, "Anthropic")
return (None, None)
+
+ async def get_flows_updates_available(self, user_id: str | None = None) -> list[dict[str, Any]]:
+ """
+ Check for available flow updates.
+ Uses cached update results from startup/previous checks if available.
+ Surfaces all available updates regardless of locked status.
+ """
+ target_user = user_id or "default"
+ if not hasattr(self, "_custom_updates_cache") or self._custom_updates_cache is None:
+ flow_configs = [
+ ("nudges", NUDGES_FLOW_ID),
+ ("retrieval", LANGFLOW_CHAT_FLOW_ID),
+ ("ingest", LANGFLOW_INGEST_FLOW_ID),
+ ("url_ingest", LANGFLOW_URL_INGEST_FLOW_ID),
+ ]
+ cache = []
+ for flow_type, flow_id in flow_configs:
+ update_info = await self._check_flow_update(flow_type, flow_id)
+ if update_info:
+ cache.append(update_info)
+ self._custom_updates_cache = cache
+
+ updates = []
+ for item in self._custom_updates_cache:
+ is_dismissed = False
+ if hasattr(self, "_dismissed_updates") and isinstance(self._dismissed_updates, dict):
+ is_dismissed = item["flow_type"] in self._dismissed_updates.get(target_user, set())
+ updates.append(
+ {
+ **item,
+ "dismissed": is_dismissed,
+ }
+ )
+
+ return updates
+
+ async def bulk_update_flows(self, flow_types: list[str], backup_custom: bool = True):
+ """
+ Bulk updates multiple flows.
+ If backup_custom is True, flows are backed up in Langflow before resetting.
+ Local file backups are always saved via _backup_flow prior to resetting.
+ Returns the backup flow details if any.
+ """
+ results: list[dict[str, Any]] = []
+ flow_configs_dict = {
+ "nudges": NUDGES_FLOW_ID,
+ "retrieval": LANGFLOW_CHAT_FLOW_ID,
+ "ingest": LANGFLOW_INGEST_FLOW_ID,
+ "url_ingest": LANGFLOW_URL_INGEST_FLOW_ID,
+ }
+
+ for flow_type in flow_types:
+ flow_id = flow_configs_dict.get(flow_type)
+ if not flow_id:
+ results.append(
+ {"flow_type": flow_type, "success": False, "error": "Invalid flow_type"}
+ )
+ continue
+
+ flow_lock = await self._get_flow_lock(flow_id)
+ async with flow_lock:
+ backup_path = None
+ backup_flow_id = None
+ flow_check_ok = False
+
+ try:
+ response = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")
+ if response.status_code == 200:
+ flow_check_ok = True
+ flow_data = response.json()
+
+ # Always attempt local file backup for safety
+ backup_path = await self._backup_flow(flow_id, flow_type, flow_data)
+
+ if backup_custom:
+ logger.info(f"Backing up flow {flow_type} in Langflow before update.")
+ # Create a backup flow directly in Langflow
+ backup_payload = dict(flow_data)
+ backup_payload.pop("id", None)
+ flow_name = flow_data.get("name", flow_type.capitalize())
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
+ backup_payload["name"] = f"Backup - {flow_name} ({timestamp})"
+ backup_payload["description"] = (
+ f"Backup of flow '{flow_name}' created before flow update on {timestamp}. "
+ "Use this flow to reference or redo your modifications."
+ )
+ backup_payload["locked"] = False
+
+ lf_create_res = await clients.langflow_request(
+ "POST", "/api/v1/flows/", json=backup_payload
+ )
+ if lf_create_res.status_code in (200, 201):
+ created_flow = lf_create_res.json()
+ backup_flow_id = created_flow.get("id")
+ logger.info(
+ f"Created backup flow in Langflow for {flow_type}: '{backup_payload['name']}' (ID: {backup_flow_id})"
+ )
+ else:
+ logger.warning(
+ f"Failed to create backup flow in Langflow for {flow_type}: HTTP {lf_create_res.status_code}"
+ )
+ except Exception as e:
+ logger.error(f"Failed to check/backup flow {flow_id} before update: {e}")
+
+ if not flow_check_ok:
+ logger.error(
+ f"Pre-flight check failed for flow {flow_type}; aborting update to protect flow modifications."
+ )
+ results.append(
+ {
+ "flow_type": flow_type,
+ "success": False,
+ "error": "Pre-flight check failed; update aborted to avoid losing changes",
+ "backup_path": None,
+ "backup_flow_id": None,
+ }
+ )
+ continue
+
+ # If backup_custom is enabled, abort update if BOTH backups failed
+ if backup_custom and backup_path is None and backup_flow_id is None:
+ logger.error(
+ f"Backup failed for flow {flow_type}; aborting update to protect flow modifications."
+ )
+ results.append(
+ {
+ "flow_type": flow_type,
+ "success": False,
+ "error": "Backup failed; update aborted to avoid losing changes",
+ "backup_path": None,
+ "backup_flow_id": None,
+ }
+ )
+ continue
+
+ try:
+ reset_res = await self._reset_langflow_flow_locked(flow_type, flow_id)
+ if reset_res.get("success"):
+ self.clear_dismissed_update(flow_type)
+ results.append(
+ {
+ "flow_type": flow_type,
+ "success": reset_res.get("success", False),
+ "error": reset_res.get("error"),
+ "backup_path": backup_path,
+ "backup_flow_id": backup_flow_id,
+ }
+ )
+ except Exception as e:
+ results.append(
+ {
+ "flow_type": flow_type,
+ "success": False,
+ "error": str(e),
+ "backup_path": backup_path,
+ "backup_flow_id": backup_flow_id,
+ }
+ )
+
+ if results and any(r.get("success") for r in results):
+ self._custom_updates_cache = None
+ try:
+ config = get_openrag_config()
+ if config.edited:
+ from api.settings import reapply_all_settings
+
+ await reapply_all_settings()
+ except Exception as e:
+ logger.error(f"Error reapplying settings after bulk update: {e}")
+
+ return results
diff --git a/src/services/startup_orchestrator.py b/src/services/startup_orchestrator.py
index 88ca22095..bbab18c75 100644
--- a/src/services/startup_orchestrator.py
+++ b/src/services/startup_orchestrator.py
@@ -170,13 +170,11 @@ async def startup_tasks(services) -> None:
# Update MCP server URLs (patch localhost and convert to streamable HTTP)
await _update_mcp_server_urls(services["langflow_mcp_service"])
- # Ensure all configured flows exist in Langflow (create-only, never overwrites).
- # This replaces LANGFLOW_LOAD_FLOWS_PATH, which performed a blind upsert on
- # every container start and discarded any user edits made in the Langflow UI.
- newly_created: set[str] = set()
+ # Ensure all configured flows exist in Langflow (create-only, never overwrites existing).
+ # If a flow does not exist, it is created and active configuration settings are reapplied.
try:
flows_service = services["flows_service"]
- newly_created = await flows_service.ensure_flows_exist()
+ await flows_service.ensure_flows_exist()
except Exception as e:
logger.error(
"Failed to ensure Langflow flows exist at startup — "
@@ -196,39 +194,3 @@ async def startup_tasks(services) -> None:
"Failed to ensure required Langflow global variables at startup",
error=str(e),
)
-
- # Check if flows were reset and reapply settings if config is edited
- try:
- config = get_openrag_config()
- if config.edited:
- logger.info("Checking if Langflow flows were reset")
- flows_service = services["flows_service"]
- reset_flows = await flows_service.check_flows_reset()
- # Exclude flows that were just seeded — they match the JSON by design,
- # not because they were externally reset.
- reset_flows = [f for f in reset_flows if f not in newly_created]
-
- if reset_flows:
- logger.info(
- f"Detected reset flows: {', '.join(reset_flows)}. Reapplying all settings."
- )
- await TelemetryClient.send_event(
- Category.FLOW_OPERATIONS, MessageId.ORB_FLOW_RESET_DETECTED
- )
- from api.settings import reapply_all_settings
-
- await reapply_all_settings(session_manager=services["session_manager"])
- logger.info("Successfully reapplied settings after detecting flow resets")
- await TelemetryClient.send_event(
- Category.FLOW_OPERATIONS, MessageId.ORB_FLOW_SETTINGS_REAPPLIED
- )
- else:
- logger.info("No flows detected as reset, skipping settings reapplication")
- else:
- logger.debug("Configuration not yet edited, skipping flow reset check")
- except Exception as e:
- logger.error(f"Failed to check flows reset or reapply settings: {str(e)}")
- await TelemetryClient.send_event(
- Category.FLOW_OPERATIONS, MessageId.ORB_FLOW_RESET_CHECK_FAIL
- )
- # Don't fail startup if this check fails
diff --git a/tests/unit/services/test_flows_service_bulk_update.py b/tests/unit/services/test_flows_service_bulk_update.py
new file mode 100644
index 000000000..1267f3f7c
--- /dev/null
+++ b/tests/unit/services/test_flows_service_bulk_update.py
@@ -0,0 +1,259 @@
+"""Tests for flows_service bulk_update_flows with Langflow backup creation."""
+
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+from services.flows_service import FlowsService # noqa: E402
+
+
+async def test_bulk_update_flows_creates_backup_flow_in_langflow():
+ service = FlowsService()
+
+ mock_get_response = MagicMock()
+ mock_get_response.status_code = 200
+ mock_get_response.json.return_value = {
+ "id": "flow-retrieval-123",
+ "name": "Custom Retrieval Flow",
+ "locked": False,
+ "data": {"nodes": []},
+ }
+
+ mock_post_response = MagicMock()
+ mock_post_response.status_code = 201
+ mock_post_response.json.return_value = {
+ "id": "backup-flow-999",
+ "name": "Backup - Custom Retrieval Flow (2026-07-23 20:00)",
+ }
+
+ async def mock_langflow_request(method, url, json=None, **kwargs):
+ if method == "GET":
+ return mock_get_response
+ elif method == "POST":
+ # Verify the posted backup payload
+ assert "id" not in json
+ assert json["name"].startswith("Backup - Custom Retrieval Flow")
+ assert json["locked"] is False
+ return mock_post_response
+ return MagicMock(status_code=404)
+
+ with (
+ patch("services.flows_service.clients.langflow_request", side_effect=mock_langflow_request),
+ patch.object(
+ service, "_backup_flow", new_callable=AsyncMock, return_value="/tmp/backup.json"
+ ),
+ patch.object(
+ service,
+ "_reset_langflow_flow_locked",
+ new_callable=AsyncMock,
+ return_value={"success": True},
+ ),
+ ):
+ results = await service.bulk_update_flows(["retrieval"], backup_custom=True)
+
+ assert len(results) == 1
+ res = results[0]
+ assert res["flow_type"] == "retrieval"
+ assert res["success"] is True
+ assert res["backup_flow_id"] == "backup-flow-999"
+
+
+async def test_bulk_update_flows_aborts_reset_on_backup_failure():
+ service = FlowsService()
+
+ mock_get_response = MagicMock()
+ mock_get_response.status_code = 200
+ mock_get_response.json.return_value = {
+ "id": "flow-retrieval-123",
+ "name": "Custom Retrieval Flow",
+ "locked": False,
+ "data": {"nodes": []},
+ }
+
+ mock_post_response = MagicMock()
+ mock_post_response.status_code = 500
+
+ async def mock_langflow_request(method, url, json=None, **kwargs):
+ if method == "GET":
+ return mock_get_response
+ elif method == "POST":
+ return mock_post_response
+ return MagicMock(status_code=404)
+
+ reset_mock = AsyncMock(return_value={"success": True})
+
+ with (
+ patch("services.flows_service.clients.langflow_request", side_effect=mock_langflow_request),
+ patch.object(service, "_backup_flow", new_callable=AsyncMock, return_value=None),
+ patch.object(service, "_reset_langflow_flow_locked", reset_mock),
+ ):
+ results = await service.bulk_update_flows(["retrieval"], backup_custom=True)
+
+ assert len(results) == 1
+ res = results[0]
+ assert res["flow_type"] == "retrieval"
+ assert res["success"] is False
+ assert "Backup failed" in res["error"]
+ assert reset_mock.call_count == 0
+
+
+async def test_bulk_update_flows_saves_local_file_backup_for_default_flows():
+ service = FlowsService()
+
+ mock_get_response = MagicMock()
+ mock_get_response.status_code = 200
+ mock_get_response.json.return_value = {
+ "id": "flow-retrieval-123",
+ "name": "Default Retrieval Flow",
+ "locked": True,
+ "data": {"nodes": []},
+ }
+
+ backup_mock = AsyncMock(return_value="/tmp/backup_default.json")
+ reset_mock = AsyncMock(return_value={"success": True})
+
+ with (
+ patch("services.flows_service.clients.langflow_request", return_value=mock_get_response),
+ patch.object(service, "_backup_flow", backup_mock),
+ patch.object(service, "_reset_langflow_flow_locked", reset_mock),
+ ):
+ results = await service.bulk_update_flows(["retrieval"], backup_custom=True)
+
+ assert len(results) == 1
+ assert results[0]["success"] is True
+ assert backup_mock.call_count == 1
+ assert reset_mock.call_count == 1
+
+
+async def test_bulk_update_flows_aborts_when_preflight_get_fails():
+ """Verify issue (2a): pre-flight GET failure aborts update without attempting reset."""
+ service = FlowsService()
+
+ mock_get_response = MagicMock()
+ mock_get_response.status_code = 500
+
+ reset_mock = AsyncMock(return_value={"success": True})
+
+ with (
+ patch("services.flows_service.clients.langflow_request", return_value=mock_get_response),
+ patch.object(service, "_reset_langflow_flow_locked", reset_mock),
+ ):
+ results = await service.bulk_update_flows(["retrieval"], backup_custom=True)
+
+ assert len(results) == 1
+ res = results[0]
+ assert res["flow_type"] == "retrieval"
+ assert res["success"] is False
+ assert "Pre-flight check failed" in res["error"]
+ assert reset_mock.call_count == 0
+
+
+def test_per_user_dismissal_isolation():
+ """Verify issue (2c): dismissal for user A does not dismiss for user B."""
+ service = FlowsService()
+
+ service.dismiss_flows_updates(["retrieval"], user_id="user_A")
+
+ assert "user_A" in service._dismissed_updates
+ assert "retrieval" in service._dismissed_updates["user_A"]
+ assert (
+ "user_B" not in service._dismissed_updates
+ or "retrieval" not in service._dismissed_updates.get("user_B", set())
+ )
+
+
+async def test_bulk_update_flows_dismissal_cleared_only_on_success():
+ """Verify issue (4c): dismissal state is preserved on failure and cleared on success."""
+ service = FlowsService()
+
+ # Pre-dismiss update for user_A
+ service.dismiss_flows_updates(["retrieval"], user_id="user_A")
+ assert "retrieval" in service._dismissed_updates["user_A"]
+
+ mock_get_fail = MagicMock(status_code=500)
+
+ # 1. Update fails (pre-flight GET returns 500) -> dismissal remains intact
+ with patch("services.flows_service.clients.langflow_request", return_value=mock_get_fail):
+ results = await service.bulk_update_flows(["retrieval"], backup_custom=True)
+
+ assert results[0]["success"] is False
+ assert "retrieval" in service._dismissed_updates.get("user_A", set())
+
+ # 2. Update succeeds -> dismissal is cleared
+ mock_get_ok = MagicMock(status_code=200)
+ mock_get_ok.json.return_value = {
+ "id": "flow-retrieval-123",
+ "name": "Retrieval Flow",
+ "locked": True,
+ "data": {"nodes": []},
+ }
+
+ with (
+ patch("services.flows_service.clients.langflow_request", return_value=mock_get_ok),
+ patch.object(service, "_backup_flow", AsyncMock(return_value="/tmp/backup.json")),
+ patch.object(
+ service, "_reset_langflow_flow_locked", AsyncMock(return_value={"success": True})
+ ),
+ ):
+ results = await service.bulk_update_flows(["retrieval"], backup_custom=True)
+
+ assert results[0]["success"] is True
+ assert "retrieval" not in service._dismissed_updates.get("user_A", set())
+
+
+async def test_ensure_flows_exist_does_not_auto_update_on_startup():
+ """Verify that existing flows are skipped on startup and never auto-updated."""
+ service = FlowsService()
+
+ mock_get_ok = MagicMock(status_code=200)
+ mock_get_ok.json.return_value = {
+ "id": "flow-retrieval-123",
+ "name": "Retrieval Flow",
+ "locked": True,
+ "updated_at": "2020-01-01T00:00:00Z",
+ }
+
+ reset_mock = AsyncMock()
+ backup_mock = AsyncMock()
+
+ with (
+ patch("services.flows_service.clients.langflow_request", return_value=mock_get_ok),
+ patch.object(service, "_backup_flow", backup_mock),
+ patch.object(service, "_reset_langflow_flow_locked", reset_mock),
+ ):
+ created = await service.ensure_flows_exist()
+
+ assert created == set()
+ assert backup_mock.call_count == 0
+ assert reset_mock.call_count == 0
+
+
+async def test_get_flows_updates_available_includes_all_flows():
+ """Verify that get_flows_updates_available surfaces updates regardless of locked status."""
+ service = FlowsService()
+
+ mock_update_info = {
+ "flow_type": "retrieval",
+ "flow_id": "flow-retrieval-123",
+ "is_custom": False,
+ }
+
+ with patch.object(service, "_check_flow_update", AsyncMock(return_value=mock_update_info)):
+ updates = await service.get_flows_updates_available()
+
+ assert len(updates) == 4
+ assert all(u["flow_type"] in ["nudges", "retrieval", "ingest", "url_ingest"] for u in updates)